目录
题目
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.
Note
- 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).
解决方案
1 | class MyStack { |
注意事项
- 使用两个队列实现栈。
- 思路是:对于push()操作,直接向第一个队列push即可;对于pop()操作,如果第一个队列的大小大于1,则将第一个队列的元素弹出并压入第二个队列,否则,也就是第一个队列只剩下一个元素的时候,直接将其弹出(但不压入第二个队列),最后再把第二个队列所有元素放回第一个队列;对于peek()操作,类似pop(),当第一个队列大小为1的时候,将这个元素的值赋给res,最后把第二个队列所有元素放回第一个队列。