栈的顺序存储方式的C语言实现
1 /* 2 编译器:Dev-c++ 5.4.0 3 文件名:stack.cpp 4 代码版本号:1.0 5 时间:2015-10-10 20:08:54 6 7 */ 8 #include <stdio.h> 9 #include <stdlib.h> 10 #define ERROR 0 11 #define OK 1 12 #define FALSE 0 13 #define TRUE 1 14 #define OVERFLOW -2 15 #define INIT_STACK_SIZE 100 16 #define STACK_INCREMENT 10 17 18 typedef int sElemType; 19 typedef int Status; 20 typedef struct { 21 sElemType *base; 22 sElemType *top; 23 int stackSize; 24 }sqStack; 25 26 /*初始化INIT_STACK_SIZE大小的空栈*/ 27 Status initStack(sqStack *s){ 28 s->stackSize=INIT_STACK_SIZE; 29 s->base=s->top=(sElemType *)malloc(INIT_STACK_SIZE*sizeof(sElemType)); 30 return OK; 31 } 32 33 /*销毁栈*/ 34 Status destroyStack(sqStack *s){ 35 free(s->base); 36 s->base=s->top=NULL; 37 s->stackSize=0; 38 return OK; 39 } 40 41 /*把S栈置为空栈*/ 42 Status clearStack(sqStack *s){ 43 s->base=s->top; 44 return OK; 45 } 46 47 /*判断栈是否为空栈*/ 48 bool emptyStack(sqStack *s){ 49 if(s->base==s->top) 50 return TRUE; 51 else 52 return FALSE; 53 } 54 55 int stackLength(sqStack *s){ 56 return s->top-s->base; 57 } 58 /*入栈*/ 59 Status push(sqStack *s,sElemType e){ 60 if(s->top-s->base>=(s->stackSize-1)) 61 { 62 s->base=(sElemType *)realloc(s->base,(INIT_STACK_SIZE+STACK_INCREMENT)*sizeof(sElemType)); 63 s->top=s->base+s->stackSize-1; 64 s->stackSize+=STACK_INCREMENT; 65 } 66 *(s->top)=e; 67 s->top++; 68 return OK; 69 } 70 71 /*出栈*/ 72 Status pop(sqStack *s,sElemType *e){ 73 if(s->base==s->top) 74 return ERROR; 75 *e=*--s->top; 76 return OK; 77 } 78 79 /*得到栈顶元素*/ 80 Status getTop(sqStack s,sElemType *e){ 81 if(s.base==s.top) 82 return ERROR; 83 *e=*(s.top-1); 84 return OK; 85 } 86 87 int visit(sElemType c){ 88 printf("%d ",c); 89 return 1; 90 } 91 /*遍历栈*/ 92 Status stackTraverse(sqStack *s,int (*visit)(sElemType)){ 93 for(sElemType *i=s->base;i<s->top;i++){ 94 visit(*i); 95 } 96 return OK; 97 } 98 99 int main(){ 100 sqStack S; 101 initStack(&S); 102 printf("\n请输入您想入栈数据的个数:"); 103 int m; 104 sElemType e; 105 scanf("%d",&m); 106 for(int i=1;i<=m;i++){ 107 printf("\n请输入第%d个数据",i); 108 scanf("%d",&e); 109 push(&S,e); 110 } 111 112 stackTraverse(&S,visit); 113 printf("\n弹出一个数据后"); 114 pop(&S,&e); 115 stackTraverse(&S,visit); 116 printf("\n得到的栈顶元素:"); 117 getTop(S,&e); 118 printf("%d\n",e); 119 printf("栈的长度为%d",stackLength(&S)); 120 121 122 system("pause"); 123 return 0; 124 }