用两个队列实现栈结构

思路:首先定义一个date队列,然后定义一个help队列,help队列辅助date队列。

push:每次加数时,加入到date队列中。

pop:先将date队列中的前n-1个数(留下最后一个数在date队列)转到help队列中去,然后给用户返回date队列中的最后一个数,最后将date队列和help队列换个引用(即原先的date队列是现在的help队列,原先的help队列是现在的date队列)。

代码如下:

 #include<bits/stdc++.h>
 using namespace std;
 int n;
 string a;
 queue< int > date,help;
 void swap()//交换两个队列的引用
 {
    queue< int > temp;
    temp=date;
    date=help;
    help=temp;
 }
 void push(int n)
 {
     date.push(n);
 }
 int pop()//每次执行pop时,help队列中都是没有数的
 {
     if(date.empty())//如果date队列中没有数,说明整个栈中都没有数,无法输出,给用户报错
         return 0;
     while(date.size()>1)//将date队列中的前n-1个数放到help队列中去,留下date队列中的最后一个数
     {
         help.push(date.front());
         date.pop();
     }
     int ans=date.front();
     date.pop();
     swap();//交换引用,此时原先的date队列就是现在的help队列,原先的help队列就是现在的date队列
     return ans;//给用户返回date队列中最后一个数
 }
 int main()
 {
     while (cin>>a)
     {
         if(a=="push")
         {
             cin>>n;
             push(n);
         }
         if(a=="pop")
         {
             int c=pop();
             if(c!=0)
                cout<<c<<endl;
             else
                cout<<"error"<<endl;
         }
     }
 }

猜你喜欢

转载自blog.csdn.net/qq_40938077/article/details/80177161