考察知识点:栈和队列

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

题解

分析

复习一下:

  1. 栈只有一头进出,先进后出
  2. 队列一头进,另一头出,先进先出

入队:将数进栈 A
出队:判断栈 B 是否为空,当栈 B 不空,出栈栈顶元素;当栈 B 空时,将栈 A 全部元素 push 进栈 B,再出栈栈顶元素

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        if(stack2.empty()){
            while(!stack1.empty()){
                int newNode = stack1.top();
                stack1.pop();
                stack2.push(newNode);
            }
        }
        int newNode = stack2.top();
        stack2.pop();
        return newNode;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};