题目在这:https://leetcode-cn.com/problems/implement-stack-using-queues/
思路分析:
题目给了一堆函数,让你实现栈的功能,但只能使用队列函数,也就是用队列实现先进后出。
题目关键点就在于,存入栈的时候如何保存数据 才能让出队列的时候像栈一样是先进后出的。
两个队列实现先进后出:
1.进来的元素先加入到辅助队列。
2.判断主队列是否为空,若不为空,则将主队列的值弹出、加入到辅助队列。 一直重复此步骤直到主队列为空为止。
3.此时所有元素都在辅队列,主队列为空,交换主副队列元素。
主队列非空的情况:
循环将主队列元素全放到辅助队列,然后交换主辅队列元素。
最后输出主队列元素即可实现 先进后出。
其他函数直接return就行了。
完整代码
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.qu1 = collections.deque()
self.qu2 = collections.deque()
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.qu2.append(x)
while self.qu1:
self.qu2.append(self.qu1.popleft())
self.qu1, self.qu2 = self.qu2, self.qu1
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
return self.qu1.popleft()
def top(self) -> int:
"""
Get the top element.
"""
return self.qu1[0]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
# if self.qu1:
# return False
# else:
# return True
return False if self.qu1 else True