用两个栈模拟队列操作

栈是先进后出,队列是先进先出操作,用两个栈可以实现队列操作。先把数据压入其中一个栈,栈顶元素最后进入,然后在把栈里元素压入另外一个栈,则原来栈顶元素变为栈底元素,原来栈底元素变为栈顶元素,然后对第二个栈弹出操作,则弹出的就是最先进入第一个栈的元素了,这就实现了队列操作,先进先出。

#include<iostream>
using namespace std;
struct stack{
    int data[5];
    int top;
}s1,s2;
struct queue{
    int data[5];
    int tail;
    int first;
}q;
int main(){

    s1.top=0;
    s2.top=0;
    q.first=q.tail=0;
    //往栈1输入数据和队列输入数据
    for(int i = 0; i < 5; i++){
        cin>>s1.data[s1.top];
        q.data[q.tail]=s1.data[s1.top];
        q.tail++;
        s1.top++;
    }
    //栈1数据弹出至栈2
    while(s1.top > 0){
        s1.top--;
        s2.data[s2.top] = s1.data[s1.top];
        s2.top++;
    }
    //栈2数据弹出
    while(s2.top > 0){
        s2.top--;
        cout<<s2.data[s2.top]<<endl;
    }
    //队列操作
    while(q.first<q.tail){
        cout<<q.data[q.first]<<" ";
        q.first++;
    }
    cout<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值