#include"stdio。h"
#include"malloc。h"
#include"stdlib。h"
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define TRUE 1
#define FALSE 0
typedef char ElemType;
typedef int Status;
#define STACK_INIT_SIZE 100 //存储空间初始分配量
#define STACKINCREMENT 10 //存储空间分配增量
typedef struct
{
ElemType *base; //在栈构造和销毁之后,base的值为NULL
ElemType *top; //栈顶指针
int stacksize; //当前已分配的存储空间,以元素为单位
}SqStack;
// 构造一个空栈S
Status InitStack(SqStack &S)
{
S。
base=(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(!S。base) //存储分配失败
exit (OVERFLOW);
S。
top=S。base;
S。stacksize=STACK_INIT_SIZE;
return OK;
}//InitStack
/// 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR /
Status GetTop(SqStack S,ElemType &e)
{
if(S。
top==S。base)
return ERROR;
e=*(S。top-1);
return OK;
}//GetTop
// 插入元素e为新的栈顶元素 /
Status Push(SqStack &S,ElemType e)
{
if(S。
top-S。base>=S。stacksize) //栈满,追加存储空间
{
S。base=(ElemType *)realloc(S。base,(S。stacksize STACKINCREMENT) * sizeof(ElemType));
if(!S。
base)
exit (OVERFLOW);
S。top=S。base S。stacksize;
S。stacksize =STACKINCREMENT;
}
*S。
top =e;
return OK;
}//Push
// 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
Status Pop(SqStack &S,ElemType &e)
{
if(S。
top==S。base)
return ERROR;
e=*--S。top;
return OK;
}//Pop
// main() //
void main()
{
int i;
char ch,e,c;
SqStack S;
InitStack(S);
printf("1。
Push2。Pop3。GetTop4。
exit
");
while(1)
{
printf("请选择:");
scanf("%d",&i);
c=getchar(); //*****接受回车符******
switch (i)
{
case 1:
printf("请输入要插入的元素:");
scanf("%c",&ch);
Push(S,ch);
break;
case 2:
printf("弹出栈顶元素:");
Pop(S,e);
printf("%c
",e);
break;
case 3:
printf("取栈顶元素:");
GetTop(S,e);
printf("%c
",e);
break;
case 4:
exit(0);
default:
printf("ERROR!Please Reput A Number
");
}
}
}。
全部