1.Description
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.
Notes:
You must use only standard operations of a queue – which means only push to back, peek/pop from front, size, and is 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).
解读:用栈实现队列,在Python里面可以考虑使用deque
2.Solution
思路:使用双向队列dequeue
压栈:
1)使用另外的变量存储要压栈的数据,然后把原来的队列extend后面
2)只使用数据本身的队列,首先把压栈的数据append原来的队列,然后遍历前面n-1个数据,popleft同时append到这个队列中后面
弹出:双向队列popleft
top():取出双向队列的第一个元素
import collections
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self._queue=collections.deque()
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: void
"""
q=self._queue
q.append(x)#把x加入到列表中
for _ in range(len(q)-1):#把要添加的元素之前
q.append(q.popleft())
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
return self._queue.popleft()
def top(self):
"""
Get the top element.
:rtype: int
"""
return self._queue[0]
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return not len(self._queue)