#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int a[10010];
int c=-1e8;
int main()
{
int top=0; //不用指针,用index
int bottom=0;
int n;
a[0]=c; //表示栈空(因为top==bottom==0时也可能是只有一个元素的情况
cin>>n;
while(n--)
{
int ins;
scanf("%d",&ins);
if(ins==3) //存x到栈顶
{
int x;
scanf("%d",&x);
if(a[0]==c) //说明此时栈空
{
a[0]=x;
continue;
}
if(top==0) //如果栈顶是数组的首,那就需要移位
{
for(int i=++bottom;i>=1;i--)
a[i]=a[i-1];
a[0]=x;
}
else //栈顶是数组的尾
{
a[++top]=x;
}
}
else if(ins==1) //翻转
{
int temp=top;
top=bottom;
bottom=temp;
}
else if(ins==2) //栈顶出栈(题设一定不为空
{
if(top==bottom) //这种情况,一定是top==bottom==0,只剩一个元素了,出栈
{
a[0]=c; //该元素出栈就栈空了。
}
else
{
if(top==0) //如果栈顶是数组的首,要移位
{
for(int i=0;i<=bottom-1;i++)
a[i]=a[i+1];
bottom--;
}
else
{
top--;
}
}
}
else if(ins==4) //从栈底打印所有元素 或 空行
{
if(a[0]==c) //栈空时
{
cout<<endl;
continue;
}
if(bottom==0) //栈底是数组的首 正向输出
{
for(int i=0;i<=top;i++)
{
if(i!=0)
cout<<" ";
cout<<a[i];
}
cout<<endl;
}
else
{
for(int i=bottom;i>=top;i--)
{
if(i!=bottom)
cout<<" ";
cout<<a[i];
}
cout<<endl;
}
}
}
return 0;
}
之前调试一直出问题,主要在于对于“栈空”情况的处理上未全面。(因为初始时top==bottom==0,所以栈空不能也这样判断)。我的处理是栈空在top==bottom==0,还让a[0]=c(c是一个绝对不会被取到的数)。这样就拿a[0]==c来判断栈空就好了。注意对于入栈、出栈、输出栈都需要考虑这个情况进行处理,要考虑周到!
【数组模拟栈操作】超级栈
最新推荐文章于 2021-09-20 10:07:22 发布