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).
题意:
使用队列实现堆栈的push(x) ,pop(),top(),empty()操作。
只能使用一个队列的标准操作 - 这意味着只能从前面,后面,peek / pop从前面,大小,并且是空的操作是有效的。
根据您的语言,队列可能不被本机支持。您可以使用列表或deque(双端队列)来模拟队列,只要您仅使用队列的标准操作即可。可以假设所有操作都有效(例如,在空堆栈上不会调用pop或top操作)。
思路:
方法一:
用两个队列模拟一个堆栈:
1 | 队列a和b |
1 | class Stack { |
方法二:
利用双端队列,实现代码简单,但是不懂原理,效率低,真正要学习的是两个队列实现栈,以及两个栈实现队列。
1 | class Stack { |