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.
这种easy题很好通过的,就看有没有一些巧妙或者稍微进步的算法设计。
方法一: 最基本的思路
class Queue {
public:
// Push element x to the back of queue.
void push(int x) { //在stack里按queue的顺序存储,每次push都借用temp把新插入的值降到最下面
stack<int> temp;
while (!s.empty()) {
temp.push(s.top());
s.pop();
}
s.push(x);
while (!temp.empty()) {
s.push(temp.top());
temp.pop();
}
}
// Removes the element from in front of queue.
void pop(void) {
s.pop();
}
// Get the front element.
int peek(void) {
return s.top();
}
// Return whether the queue is empty.
bool empty(void) {
return s.empty();
}
private:
stack<int> s;
};
这个方法简单直接,就是强行在stack里保持queue的顺序,push比较麻烦,但其他的都是直接调用。
方法二:优化写法
不用保持固有的顺序,只要完成queue的规定动作返回或者删除正确的值就好。所以思路可以开阔些,给一个网上的算法:
class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
_new.push(x);
}
void shift() {
if (_old.empty()) {
while (!_new.empty()) {
_old.push(_new.top());
_new.pop();
}
}
}
// Removes the element from in front of queue.
void pop(void) {
shift();
_old.pop();
}
// Get the front element.
int peek(void) {
shift();
return _old.top();
}
// Return whether the queue is empty.
bool empty(void) {
return _old.empty() && _new.empty();
}
private:
stack<int> _old, _new;
};
这个方法用了两个stack, 假定一个stack是按照正确顺序排列好的,pop和top都可以直接进行,push的话到另一个stack,这样的话在很多时候这些操作都实现了O(1)的复杂度。