栈 与 队 列

本文介绍了几个实用的C++在线编译工具,包括Runoob的在线编译器、TutorialsPoint的教程以及作者推荐的OnlineGDB,方便学习者即时测试和调试代码。
摘要由CSDN通过智能技术生成

1.用<stack>头文件的简易栈

#include <stack>
#include <iostream>
using namespace std;
int main(){
    stack<int> s;//新建栈s 
    int n;//输入的个数 
    cin>>n;
    for(int i=1;i<=n;i++){
    	int a;
    	cin>>a;
    	s.push(a);//压栈 
	}
    while(!s.empty()){//如果栈为空s.empty()就会返回真 
        cout <<s.top()<<" ";
        s.pop();//删除并弹出 
    }
 
    return 0;
}
2.用<queue>头文件的简易队列
#include <iostream>
#include <queue>
using namespace std;
  
int main(){
    queue<int> q1;//新建队列q1 
    int n;//输入的个数 
    cin>>n;
    for(int i=0;i<n;i++){
    	int a;
    	cin>>a;
        q1.push(a);//入队列 
	}
    //q1.size(); 队列长度 
    //q1.back();//返回队列尾部的数据 
    for(int j=0;j<n;j++){
       int e=q1.front();//返回队列头部 
       cout<<e<<" ";
       q1.pop();//删除并弹出
    }
    return 0;
}
3.不用<stack>头文件的简易栈:
#include<bits/stdc++.h>
using namespace std;
//int k;
#define MaxSize 100
typedef struct SqStack{
    int data[MaxSize]; //存放栈中的元素
    int top; //栈顶指针
}SqStack;
 
void InitStack(SqStack &S){
    S.top = -1;
}
 
void Push(SqStack &S, int x){
    if(S.top == MaxSize-1){
        cout<<"栈满"<<endl;
        return;
    }
    S.data[++S.top] = x;
}
 
void Pop(SqStack &S, int &x){
    if(S.top == -1){
        cout<<"栈空"<<endl;
        return;
    }
    x = S.data[S.top--];
}
 
int main(){
	//cout<<"栈的大小:";
	//cin>>k;
	SqStack S;
	InitStack(S);
	cout<<"输入个数:"; 
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
    	int a;
    	cout<<"输入第"<<i<<"个数:";
    	cin>>a;
    	Push(S,a);
	}
	cout<<endl;
	cout<<"输出:"; 
	for(int i=1;i<=n;i++){
		int x;
		Pop(S,x);
		cout<<x<<" ";
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值