Implement the following operations of a stack using queues.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- empty() -- Return whether the stack is empty.
Example:
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.top(); // returns 2
stack.pop(); // returns 2
stack.empty(); // returns false
Notes:
- You must use only standard operations of a queue -- which means only
push to back
,peek/pop from front
,size
, andis empty
operations are valid. - Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
- You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
LeetCode:链接
用两个队列实现栈,队列从头出,也就是只能pop(0)!!!
因为还有其他的操作,所以用辅助栈移动完之后,再移动回主栈。那么只有主栈有值,辅助栈用完就是空的。
我们先往栈内压入一个元素a,接下来继续往栈内压入b,c两个元素。我们把它们都插入queue1。这个时候 queue1包含3个元素a,b,c其中a位于队列的头部,c位于队列的尾部。
现在我们考虑从栈内弹出一个元素。根据栈的后入先出的原则,最后被压入栈的c应该最先被弹出。由于c位于queue1的尾部,而我们每次只能从队列的头部删除元素,因此我们可以从queue1中依次删除a/b并插入到queue2中,再从queue1中删除c。这就相当于从栈中弹出元素c了。我们可以用同样的方法从栈内弹出元素b。
top操作就在主栈操作,直接append在栈之后。
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue1 = []
self.queue2 = []
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
self.queue1.append(x)
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
# copy queue1 to queue2, except the last in Queue
for i in range(len(self.queue1)-1):
self.queue2.append(self.queue1.pop(0))
# move all back to queue1
for i in range(len(self.queue2)):
self.queue1.append(self.queue2.pop(0))
return self.queue1.pop(0)
def top(self):
"""
Get the top element.
:rtype: int
"""
# 只用了一个队列实现
for i in range(len(self.queue1)):
top = self.queue1.pop(0)
self.queue1.append(top)
return top
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return not self.queue1
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()