题目
implement-queue-using-stacks/
算法
* 直接模拟
* 优化
代码
* 直接模拟
class Queue {
public:
void push(int x) {
stack<int> tmp;
while (!s.empty()) {
tmp.push(s.top());
s.pop();
}
s.push(x);
while (!tmp.empty()) {
s.push(tmp.top());
tmp.pop();
}
}
void pop(void) {
s.pop();
}
int peek(void) {
return s.top();
}
bool empty(void) {
return s.empty();
}
private:
stack<int> s;
};
* 优化
class Queue {
public:
void push(int x) {
_new.push(x);
}
void shiftStack() {
if (_old.empty()) {
while (!_new.empty()) {
_old.push(_new.top());
_new.pop();
}
}
}
void pop(void) {
shiftStack();
if (!_old.empty()) _old.pop();
}
int peek(void) {
shiftStack();
if (!_old.empty()) return _old.top();
return 0;
}
bool empty(void) {
return _old.empty() && _new.empty();
}
private:
stack<int> _old, _new;
};