day 4 两栈实现队列

来源:互联网 发布:python画图代码 编辑:程序博客网 时间:2024/06/01 07:33

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


/*@param day 4 6-16 周五。
思路:将s1,s2 作为维护的数组,
s1作为存储组,s2做缓冲组。
*/
class Solution
{
public:
    void push(int node) {
        //进栈,判断是否为空
        //入队时,将元素压入栈1,
        //出队时,删除栈2元素;
        //思路:入队时,先判断栈1是否为空,若不为空则压入到栈2;
       /* int tmp;
        //栈1为空,栈2也为空,入栈1
        //栈1不为空。栈2
        if(!stack1.empty())
        {
       
            //node 压入队列中去。
            satck1.push(node);
        }
        else
            {
             while(!stack2.empty()) 
                   { 
                      //栈2入栈1。
                       tmp=stack2.top();
                       stack1.push(tmp);
                       stack2.pop();
                    } 
                  stack2.push(node);
            
            }*/
        stack1.push(node);
        


        
    }
//可供出列的元素是否有。即两个栈为空的情况下,
    int pop() {
        //两栈为空的情况
        int val;
        if(stack1.empty()&&stack2.empty())  return -1;
        //p判断栈2是否为空。若为空,则从栈1里拿元素。
          //全部拿元素
         if(stack2.empty()) 
         {
             while(!(stack1.empty()))
                 {
                   stack2.push(stack1.top());
                   stack1.pop();
                 }
             //出栈
              val=stack2.top();
              stack2.pop();
           
          }
        else{
              val=stack2.top();
              stack2.pop();
            }
        return val;
             
        
    }


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