c++:队列和栈

队列和栈是两种重要的数据结构,它们具有push k和pop操作。push k是将数字k加入到队列或栈中,pop则是从队列和栈取一个数出来。队列和栈的区别在于取数的位置是不同的。
队列是先进先出的:把队列看成横向的一个通道,则push k是将k放到队列的最右边,而pop则是从队列的最左边取出一个数。
栈是后进先出的:把栈也看成横向的一个通道,则push k是将k放到栈的最右边,而pop也是从栈的最右边取出一个数。
假设队列和栈当前从左至右都含有1和2两个数,则执行push 5和pop操作示例图如下:
push 5 -> pop
队列 1 2 -------> 1 2 5 ------> 2 5
push 5 -> pop
栈 1 2 -------> 1 2 5 ------> 1 2

Input
第一行为m,表示有m组测试输入,m<100。
每组第一行为n,表示下列有n行push k或pop操作。(n<150)
接下来n行,每行是push k或者pop,其中k是一个整数。
(输入保证同时在队列或栈中的数不会超过100个)
Output
对每组测试数据输出两行,正常情况下,第一行是队列中从左到右存的数字,第二行是栈中从左到右存的数字。若操作过程中队列或栈已空仍然收到pop,则输出error。输出应该共2*m行。

Sample Input
2
4
push 1
push 3
pop
push 5
1
pop
Sample Output
3 5
1 5
error
error

注意细节!

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<stack>
#include<queue>
using namespace std;
int main()
{
    stack<int>s;
    queue<int>q;
    string ch;
    int arr[100];
    int m,n,x,t1,t2;
    cin>>m;
    while(m--)
    {
        t1=1,t2=1;
        while(!s.empty())
            s.pop();
        while(!q.empty())
            q.pop();
        cin>>n;
        while(n--)
        {
            cin>>ch;
            if(ch=="push")
            {
                cin>>x;
                s.push(x);
                q.push(x);
            }
            else
            {
                if(!q.empty())
                    q.pop();
                else
                    t1=0;
                if(!s.empty())
                    s.pop();
                else
                    t2=0;
            }
        }
        if(t1==1)
        {
            while(!q.empty())
            {
                cout<<q.front()<<" ";
                q.pop();
            }
        }
        else
            cout<<"error";
        cout<<endl;
        if(t2==1)
        {
            int i=0;
            while(!s.empty())
            {
                arr[i++]=s.top();                    //栈是逆向输出
                s.pop();
            }
            for(int j=i-1;j>=0;j--)
                cout<<arr[j]<<" ";
        }
        else
            cout<<"error";
        cout<<endl;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值