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;
}