[剑指Offer]9-用两个栈实现队列

时间:2023-03-09 03:48:07
[剑指Offer]9-用两个栈实现队列

题目链接

https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tqId=11158&tPage=1&rp=2&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

题意

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

解题思路

画图理解。

待做

用两个队列可实现栈。

代码

class Solution
{
public:
void push(int node) {
stack1.push(node);
} int pop() {
if (stack2.empty()) {
while (!stack1.empty()) {
int temp = stack1.top();
stack1.pop();
stack2.push(temp);
}
}
if (stack2.empty()) {
throw "the queue is empty!";
}
int node = stack2.top();
stack2.pop();
return node;
} private:
stack<int> stack1;
stack<int> stack2;
};