设置两个栈,一个用来入队,一个用来出队列。
入队列:直接将元素stack1即可
出队列:如果stack2 不为空,则直接pop,否则先将stack1的元素全部弹出,然后全部压入stack2,然后将stack2的元素全部弹出。
class Solution
{
public:
//入队列
void push(int node) {
stack1.push(node);
}
//出队列
int pop() {
int result{-1};//栈底指针为-1
if(stack2.empty())
{
while(!stack1.empty())
{
stack2.push(stack1.top());//栈1元素进入栈2
stack1.pop();//栈1元素出栈
}
}
result=stack2.top();//栈2栈顶元素为出队列元素
stack2.pop();//栈2出栈
return result;
}
private:
stack<int> stack1;
stack<int> stack2;
};