用两个栈实现队列

题目描述

用两个栈来实现一个队列,完成队列的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;

}
原文地址:https://www.cnblogs.com/omelet/p/6648391.html