一、问题描述
时间限制:1秒空间限制:32768K
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
二、 思路
深入理解栈的先入先出特性。在弹出操作时,如果栈2不为空,将栈1的数据全部入栈到栈2,然后才从栈2弹出。
三、代码
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.size() <= 0){
while(stack1.size() > 0){
int & data = stack1.top();
stack1.pop();
stack2.push(data);
}
}
if(stack2.size() == 0){
printf("intput error");
}
int m = stack2.top();
stack2.pop();
return m;
}
private:
stack<int> stack1;
stack<int> stack2;
};