2026-04-14-LeetCode刷题笔记-225-用队列实现栈
这道题的目标是:只使用队列操作,实现栈的后进先出行为。
方法一:双队列
核心思路:
q1作为主队列,q2作为备份队列。pop/top时将q1前n-1个元素移动到q2。- 此时
q1队头就是栈顶元素。 pop直接删除该元素。top读取该元素后再放回q2,保证结构不变。
class MyStack {
public:
queue<int> q1, q2;
void push(int x) {
q1.push(x);
}
int pop() {
if (q1.empty()) return -1;
int n = q1.size();
while (--n) {
q2.push(q1.front());
q1.pop();
}
int res = q1.front();
q1.pop();
swap(q1, q2);
while (!q2.empty()) q2.pop();
return res;
}
int top() {
if (q1.empty()) return -1;
int n = q1.size();
while (--n) {
q2.push(q1.front());
q1.pop();
}
int res = q1.front();
q2.push(q1.front());
q1.pop();
swap(q1, q2);
while (!q2.empty()) q2.pop();
return res;
}
bool empty() {
return q1.empty();
}
};
方法二:单队列
核心思路:
- 所有元素都在
q1。 pop/top时把前n-1个元素循环到队尾。- 剩下的队头就是栈顶。
top取值后要放回队尾,保证不删除。
class MyStack {
public:
queue<int> q1;
void push(int x) {
q1.push(x);
}
int pop() {
if (q1.empty()) return -1;
int n = q1.size();
while (--n) {
q1.push(q1.front());
q1.pop();
}
int res = q1.front();
q1.pop();
return res;
}
int top() {
if (q1.empty()) return -1;
int n = q1.size();
while (--n) {
q1.push(q1.front());
q1.pop();
}
int res = q1.front();
q1.push(q1.front());
q1.pop();
return res;
}
bool empty() {
return q1.empty();
}
};
复杂度
push:pop:top:empty:
总结
这题的关键不是 API 写法,而是明确语义:top 只能读不能删,pop 才删除。把这个区别处理对,队列模拟栈就很稳了。