【数组模拟栈操作】超级栈


#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来判断栈空就好了。注意对于入栈、出栈、输出栈都需要考虑这个情况进行处理,要考虑周到!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值