此代码可以正常运行,下附有运行区,是实实在在的类C语言
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#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语言实现的算法,通过栈结构处理从键盘输入的一系列整数。当输入的整数不等于-1时,将其压入栈中;若输入为-1,则输出栈顶元素并弹出。文章包含完整的代码和运行示例,适合对C语言和算法感兴趣的读者。
903





