栈的基本操作C语言实现.doc
/栈的根本操作#define ERROR 0#define OVERFLOW -2#define Stack_init_size 100#define Stackincrement 10#include<malloc.h>#include<stdio.h> typedef int SElemType; typedef structSElemType *base;SElemType *top;int stacksize; SqStack;void main() SElemType e;SqStack S; void InitStack(SqStack*S); /构造栈的声明void GetTop(SqStack*S,SElemType e); /取栈顶元素函数声明 void Push(SqStack*S,SElemType e); /进栈函数声明 void Pop(SqStack*S,SElemType e); /弹出栈顶元素函数声明 printf("构造一个栈并读入数据:n"); InitStack(&S); /构造栈 GetTop(&S,e); /取栈顶元素 Push(&S,e); /进栈 Pop(&S,&e); / 弹出栈顶元素 printf("n"); GetTop(&S,e); /取栈顶元素 void InitStack(SqStack*S)/构造栈int i,n;SElemType e;S->base=(SElemType*)malloc(Stack_init_size*sizeof(SElemType);/if(!S->base) void exit(OVERFLOW);S->top=S->base; S->stacksize=Stack_init_size;printf("请输入要读入栈内的数据个数:");scanf("%d",&n);if(n>=S->stacksize)S->base=(SElemType*)realloc(S->base,(S->stacksize+Stackincrement)*sizeof(SElemType);/if(!S->base) void exit(OVREFLOW);for(i=0;i<n;i+)printf("输入元素:"); scanf("%d",&e);*(S->top)=e;S->top=S->top+1;void GetTop(SqStack*S,SElemType e)/取栈顶元素函数 if(S->top=S->base) return ERROR; e=*(S->top-1); printf("取出栈顶元素:%dn",e);void Push(SqStack*S,SElemType e)/进栈函数if(S->top-S->base>=S->stacksize)S->base=(SElemType*)realloc(S->base,(S->stacksize+Stackincrement)*sizeof(SElemType); /if(!S->base) void exit(OVREFLOW); S->top=S->base+S->stacksize; S->stacksize=S->stacksize+Stackincrement; printf("请输入要插入的栈顶元素:");scanf("%d",&e);*S->top=e;S->top+; void Pop(SqStack*S,SElemType e)/弹出栈顶元素函数 if(S->top=S->base) return ERROR; S->top-; e=*S->top; printf("要删除栈顶元素:%d",e);第 4 页