题解 | #用两个栈实现队列#
用两个栈实现队列
https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
class Solution
{
public:
void push(int node) {
s1.push(node);
return;
}
int pop() {
int res;
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
// s2的顶元素
res = s2.top();
s2.pop();
// s2剩余的再pop到s1中
while (!s2.empty()) {
s1.push(s2.top());
s2.pop();
}
return res;
}
private:
stack<int> s1;
stack<int> s2;
};
2023-剑指-队列 + 栈 文章被收录于专栏
2023-剑指-队列 + 栈
