猫史档案馆


如何用栈模拟队列(c++)

用户:SCS_user_EHQ0z2l6elSCS_user_EHQ0z2l6el查看:7 回复:2 评论:7 创建时间:2022-09-10T11:53:47


话不多说

上die码

#include<iostream>
using namespace std;
const int MAXN=101;
int a1[MAXN],head1=0;//栈1
int a2[MAXN],head2=0;//栈2
void push(int n){//入队
    if(head1>=MAXN-1){//栈1已满
        cout<<"队列已满!"<<endl;
    }else{
        a1[head1]=n;
        head1++;
    }
}
void pop(){//出队
    if(head1==0&&head2==0){
        cout<<"队列里没有任何数!"<<endl;
    }else if(head2==0){
        head2=head1;
        for(int i=0;i<=head1-1;i++){
	    a2[i]=a1[head1-i-1];
	}
        head1=0;
        head2--;
        cout<<a2[head2]<<endl;
    }else{
        head2--;
        cout<<a2[head2]<<endl;
    }
}
int main(){
    push(11);
    push(45);
    pop();
    push(14);
    pop();
    pop();
    return 0;
}


回复

上一页1 页 / 共 1下一页
tiger666250tiger666250

所以说有队列你为什么要用栈呢(划掉())

点赞0


评论


囧仙_official囧仙_official

给个建议:直接用stl的stack,手写除了随机访问(狗头保命)也就稍微快了一点,但是出错率。。。

点赞0


评论