• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
煎蛋啊
博客园    首页    新随笔    联系   管理    订阅  订阅
用两个栈实现队列

题目描述

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

}

 

posted on 2017-03-30 20:39  煎蛋啊  阅读(227)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3