剑指offer_编程题_用两个栈实现队列

  • 题目
    用两个栈来实现一个队列,完成队列的Push和Pop操作。
    队列中的元素为int类型。
    
  1. stack1作为主栈
    入队时,直接进行入栈操作
    出队时,将stack1中除栈底元素压入stack2,获得stack1栈底元素后出栈
    此时,stack1为空,将stack2重新压入stack1,完成操作
    class Solution
    {
    public:
        void push(int node) {
            stack1.push(node);
        }
    
        int pop() {
            while(stack1.size()>1){
         	   int temp = stack1.top();
         	   stack1.pop();
         	   stack2.push(temp);
            }
            int res = stack1.top();
            stack1.pop();
            while(!stack2.empty()){
         	   int temp = stack2.top();
         	   stack2.pop();
         	   stack1.push(temp); 
            }
            return res;
        }
    
    private:
        stack<int> stack1;
        stack<int> stack2;
    };
    
  2. 对连续出队情况的改进
    stack1出栈压入stack2后,暂时保留stack2
    接下来执行入队操作时,再重新将stack2压入stack1
    class Solution
    {
    public:
        void push(int node) {
            if(stack1.empty()){
         	   while(!stack2.empty()){
         		   int temp = stack2.top();
         		   stack2.pop();
         		   stack1.push(temp);
         	   }
            }
            stack1.push(node);
        }
    
        int pop() {
            if(stack2.empty()){
         	   while(!stack1.empty()){
         		   int temp = stack1.top();
         		   stack1.pop();
         		   stack2.push(temp);
         	   }
            }
            int res = stack2.top();
            stack2.pop();
            return res;
        }
    
    private:
        stack<int> stack1;
        stack<int> stack2;
    };
    
发布了80 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/C_abua/article/details/105680870
今日推荐