题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路:
入队:栈1入栈,相当于元素入队
出队:判断栈2是否为空,如果为空,把栈1的元素压入栈2;栈2出栈,相当于元素出队
代码实现:
class Solution
/*
解题思路:
入队:栈1入栈,相当于元素入队
出队:判断栈2是否为空,如果为空,把栈1的元素压入栈2;栈2出栈,相当于元素出队
*/
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
if(stack2.empty()){
while(!stack1.empty()){
int x = stack1.top();
stack1.pop();
stack2.push(x);
}
}
int ans = stack2.top();
stack2.pop();
return ans;
}
private:
stack<int> stack1;
stack<int> stack2;
};