剑指Offer之用两个栈实现队列

栈的性质是先进后出,队列是先进先出。但是我们可以使用两个栈来模拟队列的操作。比如一个序列a,b,c。我们可以将其压入stack1中,stack1中的值为从栈顶到栈底为c,b,a如果此时要出队列的话,可以将stack1中得元素全部压入stack2中,弹出stack2中的头部。即为a,如果要接着输出队列的话可以将stack2里的元素接着弹出,即为b,但是,如果此时想要插入一个元素d。这是如果想着把d直接压入stack2中的话显然是不对的了,要是下次再弹出元素的话直接弹出d,但是d是最后才入列的。这里有两种方法,一种是将stack2中得元素全部压入stack1中,此时再将d压入stack1中,弹出时再将stack1中得元素压入stack2中。但是这么折腾显然效率不高。我们回到要插入d的时候。此时stack1是空的,我们可以把d压入stack1中,但是如果要弹出d时应该这么操作。此时stack2不为空,就意味着有多少元素是在d之前的,那么弹出stack2中得元素,直到为空,然后将d转而压入到stack2中。

因此我们可以这么操作,每次想要压入stack2时加一个判断,如果stack2中不为空,那么显然此时是不能压入stack2的。

方法一:每次多了一个压入stack1的过程,九度OJ超时:

#include <stdio.h>
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
   // freopen("/Users/sanyinchen/Workspaces/oc/conse/B_ali/B_ali/in.txt","r",stdin);
  
    int m;
    while(cin>>m)
    {
    stack<int> a,b;
    string mdo;
    int mid;
    for(int i=0;i<m;i++)
    {
        cin>>mdo;
        if(mdo=="PUSH")
        {
           
            cin>>mid;
            a.push(mid);
        }
       else
       {
           while(!a.empty())
           {
               b.push(a.top());
               a.pop();
           }
           if(b.empty())
           {
               cout<<"-1"<<endl;
           }
           else
           {
               cout<<b.top()<<endl;
               b.pop();
           }
           while(!b.empty())
           {
               a.push(b.top());
               b.pop();
           }
       }
    }
    
    
    }
    return 0;
}

方法二:

#include <stdio.h>
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
   //freopen("/Users/sanyinchen/Workspaces/oc/conse/B_ali/B_ali/in.txt","r",stdin);
  
    int m;
    while(cin>>m)
    {
    stack<int> a,b;
    string mdo;
    int mid;
    for(int i=0;i<m;i++)
    {
        cin>>mdo;
        if(mdo=="PUSH")
        {
           
            cin>>mid;
            a.push(mid);
        }
       else
       {
           if(b.empty())
           while(!a.empty())
           {
               b.push(a.top());
               a.pop();
           }
           if(b.empty())
           {
               cout<<"-1"<<endl;
           }
           else
           {
               cout<<b.top()<<endl;
               b.pop();
           }
          
       }
    }
    
    
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值