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

掌握思路:

  1. 队列push操作:直接将元素push进stack1即可;
  2. 队列pop操作:若stack2为空,将stack1元素分别弹出并压入stack2中,再弹出stack2栈顶元素;若stack2不为空,直接弹出stack2栈顶元素即可。
    代码:
    class Solution
    {
    public:
     void push(int node) {
         /*队尾插入:直接将元素插入s1即可
         */
         stack1.push(node);
     } 
     int pop() {
         /*队顶删除:
         当stack2不为空时,直接弹出栈顶元素即为删除,
         当stack2为空时,将stack1中元素压入stack2中,再弹出栈顶;
         */
         if(stack2.empty())
         {
             while(!stack1.empty())
             {
                 int s=stack1.top();
                 stack1.pop();
                 stack2.push(s);
             }
         }
         int s=stack2.top();
         stack2.pop();
         return s;
     }
    private:
     stack<int> stack1;
     stack<int> stack2;
    };