考点:
栈和队列
题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题:
- 1、push,将数据直接压入stack1即可;
- 2、pop,将stack1中的数据弹出压入到stack2中,则数据顺序相反,为保证最先进入的数据一直处于栈顶,
只有将stack2中的数据全部pop后,才能继续讲stack1中的数据压入到stack2中,继续做pop
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int num;
if(stack2.empty()){
while(!stack1.empty()){
num = stack1.top();
stack1.pop();
stack2.push(num);
}
}
num = stack2.top();
stack2.pop();
return num;
}
private:
stack<int> stack1;
stack<int> stack2;
};