题目
implement-stack-using-queues
算法
* 直接模拟
* 优化
代码
* 直接模拟
class Stack {
public:
void push(int x) {
q2.push(x);
while (q2.size() > 1) {
q1.push(q2.front());
q2.pop();
}
}
void pop(void) {
top();
q2.pop();
}
int top(void) {
if (q2.empty()) {
for (int i = 0; i < (int)q1.size() - 1; ++i) {
q1.push(q1.front());
q1.pop();
}
q2.push(q1.front());
q1.pop();
}
return q2.front();
}
bool empty(void) {
return q1.empty() && q2.empty();
}
private:
queue<int> q1, q2;
};
* 优化
class Stack {
public:
void push(int x) {
queue<int> tmp;
while (!q.empty()) {
tmp.push(q.front());
q.pop();
}
q.push(x);
while (!tmp.empty()) {
q.push(tmp.front());
tmp.pop();
}
}
void pop() {
q.pop();
}
int top() {
return q.front();
}
bool empty() {
return q.empty();
}
private:
queue<int> q;
};