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

来源:互联网 发布:世界各国软件行业排名 编辑:程序博客网 时间:2024/05/29 15:13

栈的性质是先进后出,队列是先进先出。但是我们可以使用两个栈来模拟队列的操作。比如一个序列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