zoukankan      html  css  js  c++  java
  • 用两个栈实现队列

    题目描述

    用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
     
    基本思想:1. 插入一个元素a,将它插入stack1中;
           2. 当弹出一个元素时:(1) 若stack2为空,而stack1不为空,则将stack1中的元素全部弹出到stack2中,然后将stack2栈顶元素弹出;
                    (2) 若stack为空且stack1也为空,return -1;
                    (3) 若stack2不为空,则直接弹出stack2的栈顶元素。
     
    #include <iostream>
    #include <algorithm>
    #include "string.h"
    #include "stdio.h"
    #include <vector>
    #include <deque>
    #include <stack>
    #include<map>
    #include<utility>
    #include "math.h"
    using namespace std;
    
    class Solution
    {
    public:
        void push(int node) {
    
            stack1.push(node);
        }
    
        int pop() {
            int res;
    
            if(stack2.empty()&&!stack1.empty())
            {
                 while(!stack1.empty())
                {
                    int p = stack1.top();
                    stack2.push(p);
                    stack1.pop();
                }
    
            }
            if(stack2.empty())
            {
                return -1;
            }
    
            res = stack2.top();
            stack2.pop();
    
            return res;
        }
    
    private:
        stack<int> stack1;
        stack<int> stack2;
    };
    int main()
    {
        vector<int> arr;
        arr.push_back(1);
        arr.push_back(2);
        arr.push_back(3);
        Solution solution;
        for(int i=0;i<arr.size();i++)
        {
            solution.push(arr[i]);
        }
        cout<<solution.pop()<<endl;
        solution.push(4);
        cout<<solution.pop()<<endl;
        cout<<solution.pop()<<endl;
        cout<<solution.pop()<<endl;
    
    }
  • 相关阅读:
    cf854B Maxim Buys an Apartment
    Snuke's Coloring 2-1
    P1087 FBI树
    Card Game for Three
    Many Formulas
    排队
    苹果消消乐(尺取法)
    猴子选大王(约瑟夫)
    进制转化
    UIProgress控件的属性和方法
  • 原文地址:https://www.cnblogs.com/omelet/p/6648391.html
Copyright © 2011-2022 走看看