当前位置 博文首页 > 進撃の算法:[Pyhon3] LeetCode 232. 用栈实现队列 - [Easy]
232. Implement Queue using Stacks
232. 用栈实现队列
(剑指offer - 9. 用两个栈实现队列)
Implement the following operations of a queue using stacks.
使用栈实现队列的下列操作:
Example:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
Notes:
说明:
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stack_in = []
self.stack_out = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.stack_in.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if self.stack_in == [] and self.stack_out == []:
return None
while self.stack_in:
self.stack_out.append(self.stack_in.pop(0))
return self.stack_out.pop(0)
def peek(self):
"""
Get the front element.
:rtype: int
"""
if self.stack_in == [] and self.stack_out == []:
return None
while self.stack_in:
self.stack_out.append(self.stack_in.pop(0))
return self.stack_out[0]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
if self.stack_in == [] and self.stack_out == []:
return True
return False
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
图解参考:https://www.cnblogs.com/xugenpeng/p/10051819.html
cs