用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路: 先将所有元素都压入stack1中
判断stack2是否为空,如果为空,将stack1中元素依次出栈,放入stack2中,如果不为空,直接先对stack2进行出栈。
class Solution{
public:
void push(int node) {
stack1.push(node); // 数据放入栈1中
}
// 将stack1出栈压入stack2
int val;
int pop() {
if(stack2.empty()){ // 栈2为空
// 栈1中有元素
while(!stack1.empty()){
val=stack1.top(); // 依次取出栈1中的元素
stack2.push(val); // 放入栈2中
stack1.pop(); // 直到取完为止
}
}
// 栈2不为空,先出栈
val=stack2.top();
stack2.pop();
return val;
}
private:
stack<int> stack1;
stack<int> stack2;
};