题目:用栈实现队列
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
- You must use only standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
题意:
用栈实现具有下列操作的队列:
1、push(x)--压入一个元素x到队列末尾;
2、pop()--删除队列最前的一个元素;
3、peek()--得到最前的一个元素;
4、empty()--返回这个队列是否为空
Note:
1、只能使用栈的标准操作函数,意思是只能使用push()栈顶,pop()或者peek()栈顶元素,是否是empty()栈操作是能使用的;
2、根据你的语言,堆栈可能不支持本地库调用。你可以使用列表或者双向队列模拟一个堆栈,只要你只使用一个堆栈的标准操作函数即可;
3、可以假定所有的操作都是有效的(例如,没有pop()或者peek()操作将会调用一个空队列);
思路一:
栈的特点是先进后出,而队列的特点是先进先出。主要是利用栈先进后出实现队列的先进先出的特点。只需要一个辅助栈,每次需要添加一个元素时,需要将栈中的元素转存到辅助栈中,保存元素到栈,再将辅助栈中的元素放回到栈中。以此来实现队列先进先出的特点。
代码:C++版:0ms
class Queue { public: // Push element x to the back of queue. void push(int x) { stack<int> tmp; //辅助栈 while (!oldStack.empty()) { //将栈转存到辅助栈,实现顺序倒换 tmp.push(oldStack.top()); oldStack.pop(); } oldStack.push(x); //将压入的数压入到栈中 while (!tmp.empty()) { //将辅助栈的内容回存到原栈中 oldStack.push(tmp.top()); tmp.pop(); } } // Removes the element from in front of queue. void pop(void) { oldStack.pop(); } // Get the front element. int peek(void) { return oldStack.top(); } // Return whether the queue is empty. bool empty(void) { return oldStack.empty(); } private: stack<int> oldStack; };
思路二:
思路一解法简单,因为每次新加入一个数都要做两次堆栈翻转的操作,所以效率很低。本思路采用两个栈_new和_old,利用_new栈存储进栈的数,利用_old栈来完成出栈及其他操作,这样就刚好将顺序转换过来了。每次当_old栈中为空的时候,将_new栈的内容翻转存储到_old栈中,以备下一次调用使用。
代码:C++版:0ms
class Queue { public: // Push element x to the back of queue. void push(int x) { _new.push(x); //新入的数都保存在_new栈中。 } void shiftStack() { if (_old.empty()) { //当_old栈为空时将_new栈的内容翻转存到_old栈中,实现先进先出 while (!_new.empty()) { _old.push(_new.top()); _new.pop(); } } } // Removes the element from in front of queue. void pop(void) { shiftStack(); if (!_old.empty()) _old.pop(); } // Get the front element. int peek(void) { shiftStack(); if (!_old.empty()) return _old.top(); return 0; } // Return whether the queue is empty. bool empty(void) { return _old.empty() && _new.empty(); } private: stack<int> _old, _new; };