Basic operations of sequential stack and sequential Stack
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 #define STACK_INIT_SIZE 10 5 #define STACKINCREASE 10 6 #define OK 1 7 #define ERROR 0 8 9 typedef int ElemType; 10 typedef int Status; 11 12 typedef struct{ 13 ElemType* base; 14 ElemType* top; 15 int InitSize; 16 }SuqStack; 17 18 Status InitStack(SuqStack* s){ 19 s->base = (ElemType *)malloc(sizeof(ElemType)*STACK_INIT_SIZE); 20 if(!s->base) 21 return ERROR; 22 s->top = s->base; 23 s->InitSize = STACK_INIT_SIZE; 24 return OK; 25 } 26 Status ClearStack(SuqStack* s){ 27 s->top = s->base; 28 return OK; 29 } 30 Status DestroyStack(SuqStack* s){ 31 int i; 32 for(i = 1; i < s->InitSize; i++){ 33 free(s->base); 34 s->base++; 35 } 36 s->base = s->top = NULL; 37 s->InitSize = 0; 38 return OK; 39 } 40 Status Pop(SuqStack* s, ElemType* result){ 41 if(s->base == s->top) 42 return ERROR; 43 *result = *(--(s->top)); 44 return OK; 45 } 46 Status Push(SuqStack* s,ElemType value){ 47 if(s->top - s->base == s->InitSize){ 48 s->base = (ElemType* )realloc(s->base,sizeof(ElemType) * (s->InitSize + STACKINCREASE)); 49 if(!s->base) 50 return ERROR; 51 s->top = s->base + STACK_INIT_SIZE; 52 s->InitSize = STACKINCREASE + STACK_INIT_SIZE; 53 printf("has a overflow"); 54 } 55 *(s->top) = value; 56 (s->top)++; 57 return OK; 58 } 59 //test 60 Status CreateStack(SuqStack* s,int size){ 61 int i; 62 for(i = 1; i <= size; i++){ 63 printf("please enter the element%d: ",i); 64 scanf("%d",(s->top)); 65 //printf("%d\n",*(s->top)); 66 (s->top)++; 67 //printf("%d\n",s->top); 68 } 69 return OK; 70 } 71 Status ShowStack_FromTop(SuqStack s){ 72 printf("\n"); 73 while(s.top != s.base){ 74 (s.top)--; 75 printf("%d ",*(s.top)); 76 } 77 printf("\n"); 78 return OK; 79 } 80 int main(){ 81 SuqStack s; 82 InitStack(&s); 83 //CreateStack(&s,5); 84 Push(&s,3); 85 Push(&s,5); 86 Push(&s,4); 87 Push(&s,1); 88 Push(&s,97); 89 Push(&s,423); 90 ShowStack_FromTop(s); 91 int r; 92 Pop(&s,&r); 93 printf("Pop is %d! ",r); 94 Pop(&s,&r); 95 printf("Pop is %d! ",r); 96 Pop(&s,&r); 97 printf("Pop is %d! ",r); 98 ShowStack_FromTop(s); 99 100 return 0;101 }