顺序栈的实现

来源:互联网 发布:触摸屏查询机软件 编辑:程序博客网 时间:2024/06/03 17:09
#include<stdio.h>#include<stdlib.h>#define STACK_INIT_SIZE 10#define STACKINCREASE 10#define OK 1#define ERROR 0typedef int ElemType;typedef int Status;typedef struct{ElemType* base;ElemType* top;int InitSize;}SuqStack;Status InitStack(SuqStack* s){s->base = (ElemType *)malloc(sizeof(ElemType)*STACK_INIT_SIZE);if(!s->base)return ERROR;s->top = s->base;s->InitSize = STACK_INIT_SIZE;return OK;}Status ClearStack(SuqStack* s){s->top = s->base;return OK;}Status DestroyStack(SuqStack* s){int i;for(i = 1; i < s->InitSize; i++){free(s->base);s->base++;}s->base = s->top = NULL;s->InitSize = 0;return OK;}Status Pop(SuqStack* s, ElemType* result){if(s->base == s->top)return ERROR;*result = *(--(s->top));return OK;}Status Push(SuqStack* s,ElemType value){if(s->top - s->base == s->InitSize){s->base = (ElemType* )realloc(s->base,sizeof(ElemType) * (s->InitSize + STACKINCREASE));if(!s->base)return ERROR;s->top = s->base + STACK_INIT_SIZE;s->InitSize = STACKINCREASE + STACK_INIT_SIZE;printf("has a overflow");}*(s->top) = value;(s->top)++;return OK;}//testStatus CreateStack(SuqStack* s,int size){int i;for(i = 1; i <= size; i++){printf("please enter the element%d: ",i);scanf("%d",(s->top));//printf("%d\n",*(s->top));(s->top)++;//printf("%d\n",s->top);}return OK;}Status ShowStack_FromTop(SuqStack s){printf("\n");while(s.top != s.base){(s.top)--;printf("%d ",*(s.top));}printf("\n");return OK;}int main(){SuqStack s;InitStack(&s);//CreateStack(&s,5);Push(&s,3);Push(&s,5);Push(&s,4);Push(&s,1);Push(&s,97);Push(&s,423);ShowStack_FromTop(s);int r;Pop(&s,&r);printf("Pop is %d!  ",r);Pop(&s,&r);printf("Pop is %d!  ",r);Pop(&s,&r);printf("Pop is %d!  ",r);ShowStack_FromTop(s);return 0;}

0 0
原创粉丝点击