- https://leetcode.com/problems/implement-stack-using-queues/
- https://leetcode-cn.com/problems/implement-stack-using-queues/
每次新元素进队列的时候,先把当前的数字进入队列,然后把它前面的所有的元素翻转一下,翻到了它的后面。
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.que = collections.deque()
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
self.que.append(x)
for i in range(len(self.que) - 1):
self.que.append(self.que.popleft())
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
return self.que.popleft()
def top(self):
"""
Get the top element.
:rtype: int
"""
return self.que[0]
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return not self.que