题解 | #用两个栈实现队列#
用两个栈实现队列
https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
class Solution
{
public:
void push(int node) {
while(!stack2.empty()) // 先判断stack2是否为空,如果为空,则将stack2中的元素转移到stack1中
{
int tmp = stack2.top();
stack2.pop();
stack1.push(tmp);
}
stack1.push(node); // stack1正常将1元素入队列
}
int pop() {
while(!stack1.empty())//出队列时,先将元素从stack1中转移到stack2中
{
int tmp = 0;
tmp = stack1.top();
stack1.pop();
stack2.push(tmp);
}
int fan = stack2.top();// 此时,stack2中的栈顶元素就是队列的队首元素
stack2.pop();
return fan;
}
private:
stack<int> stack1; // 负责入队
stack<int> stack2; // 负责出队
};
查看11道真题和解析