题目
Leetcode 225. 用队列实现栈
代码(7.17 首刷自解)
class MyStack {
public:
queue<int> q1, q2;
MyStack() {}
void push(int x) {
q1.push(x);
}
int pop() {
while(q1.size() > 1) {
q2.push(q1.front());
q1.pop();
}
int x = q1.front();
q1.pop();
swap(q1, q2);
return x;
}
int top() {
return q1.back();
}
bool empty() {
return q1.empty();
}
};
代码(9.22 二刷自解)
class MyStack {
public:
queue<int> q1, q2;
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
while(q1.size() != 1) {
q2.push(q1.front());
q1.pop();
}
int front = q1.front();
q1.pop();
swap(q1, q2);
return front;
}
int top() {
return q1.back();
}
bool empty() {
return q1.empty() && q2.empty();
}
};