栈与队列数组模拟
作者:
LYMY
,
2023-09-30 12:21:05
,
所有人可见
,
阅读 79
栈
#include<iostream>
using namespace std;
const int N=100010;
int stk[N],tt=0;
bool isempty(){
if(tt>0) return false;
else return true;
}
void push_stack(int x){
stk[++tt]=x;
}
void pop_stack(){
tt--;
}
int top(){
return stk[tt];
}
int size(){
return tt;
}
int n;
int main(){
cin>>n;
while(n--){
int x;
cin>>x;
push_stack(x);
cout<<"栈顶元素:"<<top()<<" 栈中元素个数:"<<size()<<endl;
}
while(!isempty()){
cout<<top()<<" ";
pop_stack();
}
return 0;
}
队列
#include<iostream>
using namespace std;
const int N=100010;
int q[N],hh=0,tt=-1;
bool isempty(){
if(hh<=tt) return false;
else return true;
}
void push_queue(int x){
q[++tt]=x;
}
void pop_queue(){
hh++;
}
int front(){
return q[hh];
}
int back(){
return q[tt];
}
int size(){
return (tt==-1)? 0:(tt-hh+1);
}
int n;
int main(){
cin>>n;
while(n--){
int x;
cin>>x;
push_queue(x);
cout<<"队首元素:"<<front()<<" 队尾元素:"<<back()<<" 队列元素个数: "<<size()<<endl;
}
while(!isempty()){
cout<<front()<<" ";
pop_queue();
}
return 0;
}