剑指Offer 用两个栈实现队列
时间限制:1秒 空间限制:32768K 热度指数:243863
题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
给出代码:
class Solution
{
public:
void push(int node) {
}
int pop() {
}
private:
stack<int> stack1;
stack<int> stack2;
};
栈1读入数字,然后换到栈2,注意当栈2没有数据的时候才从栈1读入数据
AC代码:
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop()
{
if(!stack2.empty()) {
int a = stack2.top();
stack2.pop();
return a;
}
else {
while(!stack1.empty()) {
int k = stack1.top();
stack2.push(k);
stack1.pop();
}
int a = stack2.top();
stack2.pop();
return a;
}
}
private:
stack<int> stack1;
stack<int> stack2;
};

浙公网安备 33010602011771号