题目:用队列实现栈
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.
- You must use only standard operations of a queue -- which means only
push to back
,peek/pop from front
,size
, andis 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).
Update (2015-06-11):
The class name of the Java function had been updated to MyStack instead of Stack.
题意:
使用队列实现队列的下列操作:
1、push()--将元素x压入栈;
2、pop()--移除栈顶元素;
3、top()--得到栈顶元素;
4、empty()--返回该栈是否是空栈;
Note:
1、只能使用队列的标准操作函数,意思是只能使用push()队列尾,pop()或者peek()队列最前的元素,队列是否是empty()操作是能使用的;
2、根据你的语言,队列可能不支持本地库调用。你可以使用列表或者双向队列模拟一个队列,只要你只使用一个队列的标准操作函数即可;
3、可以假定所有的操作都是有效的(例如,没有pop()或者top()操作将会调用一个空栈);
update:
java中使用MyStack代替Stack功能;
思路一:
该题与Implement Queue using Stacks题目类似,而且刚好相反,目的是想要使用队列的先进先出的特点模拟出堆栈先进后出的特点,主要思路类似于Implement Queue using Stacks题目思路一,使用一个辅助队列实现两次队列顺序翻转,利用队列先进先出的特点实现堆栈先进后出的特点。
代码:C++版:0ms
class Stack { public: // Push element x onto stack. void push(int x) { queue<int> tmp; //辅助队列 while (!oldQueue.empty()) { //翻转队列存储到辅助队列中 tmp.push(oldQueue.front()); oldQueue.pop(); } oldQueue.push(x); //将新增加的元素放入队列中 while (!tmp.empty()) { //翻转辅助队列存储到队列中,实现新进后出 oldQueue.push(tmp.front()); tmp.pop(); } } // Removes the element on top of the stack. void pop() { oldQueue.pop(); } // Get the top element. int top() { return oldQueue.front(); } // Return whether the stack is empty. bool empty() { return oldQueue.empty(); } private: queue<int> oldQueue; };
思路二:
类似于Implement Queue using Stacks题目思路二,采用两个队列实现,一个队列存储新加入队列的值,模拟栈顶操作,另一个队列存储值,以及通过翻转实现栈的后进先出特点。
代码:C++版:2ms
class Stack { public: // Push element x onto stack. void push(int x) { q2.push(x); while (q2.size() > 1) { //当q2队列大小大于1时,将q2队列转存到q1队列中 q1.push(q2.front()); q2.pop(); } } // Removes the element on top of the stack. void pop() { top(); q2.pop(); //删除最后加入的元素,即模拟栈顶元素删除 } // Get the top element. int top() { if (q2.empty()) { for (int i = 0; i < (int)q1.size() - 1; ++i) { //将最后一个元素换到最前面 q1.push(q1.front()); q1.pop(); } q2.push(q1.front()); //将最后放入队列的元素放入到q2队列中 q1.pop(); } return q2.front(); //放回最后放入队列的元素 } // Return whether the stack is empty. bool empty() { return q1.empty() && q2.empty(); } private: queue<int> q1, q2; };