栈的顺序储存
#include<stdio.h>#include<stdlib.h>
#define MaxStackSize 100
typedef char DateType;
typedef struct
{
DateType *base;
DateType *top;
int stacksize;
}SqStack;
int StackInitnate(SqStack *s)
{
s->base=(DateType *)malloc(MaxStackSize*sizeof(DateType));
if(!s->base)
{
printf("分配空间失败!\n");
return 0;
}
s->top=s->base;
s->stacksize=MaxStackSize;
printf("栈初始化成功!\n");
return 0;
}
int StackPush(SqStack *s)
{
DateType x;
if(s->top-s->base>=MaxStackSize)
{
printf("堆栈已满无法插入!");
return 1;
}
else
{
fflush(stdin);
printf("请输入要插入的值:");
x=getchar();
*s->top=x;
s->top++;
return 1;
}
}
int StackPop(SqStack &s,DateType *d)
{
if(s.top==s.base)
{
printf("栈为空\n");
return 0;
}
s.top--;
d=s.top;
return 1;
}
int StackTop(SqStack &s,DateType *d)
{
if(s.top==s.base)
{
printf("栈为空\n");
return 0;
}
else
{
while(s.top!=s.base)
{
d=s.top-1;
s.top=s.top-1;
printf("%c",d);
}
}
printf("\n");
}
void main()
{
int choice;
DateType e;
SqStack s;
do
{
printf("===============================\n");
printf(" 0:退出\n");
printf(" 1:初始化栈\n");
printf(" 2:入栈\n");
printf(" 3:出栈\n");
printf(" 4:读取栈顶元素\n");
printf("===============================\n");
printf("输入操作选择代码(0-4):");
scanf("%d",&choice);
while(choice<0||choice>4) {printf("输入有误,请重新输入(0-4):");scanf("%d",&choice);}
switch(choice)
{
case 0:exit(1);
case 1:StackInitnate(&s);break;
case 2:printf("2\n");StackPush(&s);break;
case 3:StackPop(s, &e);printf("出栈元素的值是:%c\n",e);break;
case 4:StackTop(s, &e);printf("栈顶元素的值是:%c\n",e);break;
}
}while(choice);
}