类C语言--栈与队列习题:设从键盘输入一整数的序列:a1, a2, a3,…,an,试编写算法实现:用栈结构存储输入的整数,当ai≠-1时,将ai进栈;当ai=-1时,输出栈顶整数并出栈。算法应对异常

此代码可以正常运行,下附有运行区,是实实在在的类C语言

#include 
#include 
#include
#define MAXSIZE 100
enum Status{ERROR,OK};
typedef int ElemType;

typedef struct
{
	ElemType *base; //起始地址
	ElemType *top;
	int stacksize;
}SqStack;

Status InitStack(SqStack &S)  //初始化
{
	S.base=(ElemType *)malloc(MAXSIZE*sizeof(ElemType));
	if(!S.base)  //申请失败
		return ERROR;  
	S.top=S.base;
	S.stacksize=MAXSIZE;
	return OK;
}

Status InOutS(SqStack &S)
{   
	ElemType e;
	int n;
	if(InitStack(S))
		printf("初始化成功\n");

   printf("输入元素个数\n");
   scanf("%d",&n);
   printf("开始入栈");
    for(int i=0;i<n;i++)
	{

	   scanf("%d",&e);
	   if(e!=-1)
	   {
          if(S.top-S.base==S.stacksize)
		  {
	          printf("栈满\n");
	          return ERROR;
		  }
		  *S.top++=e;
	   }
	   else   //读入的整数=-1时退栈
	   {
		   if(S.top==S.base)
		   {
			   printf("栈空\n");
			   return ERROR;
		   }
		   printf("%d ",*--S.top);
		   printf("\n");
	   }
   }

	printf("全部出栈\n");
	while(S.top!=S.base)
	{
		printf("%d ",*--S.top);
	}
	return OK;
}
int main()
{
	SqStack S;
	InOutS(S);
	return 0;
}
	

类C语言--栈与队列习题:设从键盘输入一整数的序列:a1, a2, a3,…,an,试编写算法实现:用栈结构存储输入的整数,当ai≠-1时,将ai进栈;当ai=-1时,输出栈顶整数并出栈。算法应对异常_第1张图片

你可能感兴趣的:(栈)