栈的基本操作
栈的基本操作
1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #define StackSize 100 5 #define Sizeincrease 10 6 7 typedef int SElemtype; 8 typedef struct{ 9 SElemtype *base; 10 SElemtype *top; 11 int stacksize; 12 }SqStack; 13 SElemtype e; 14 15 SElemtype Initial(SqStack &S) 16 { 17 S.base=(SElemtype *)malloc(StackSize*sizeof(SElemtype)); 18 if(!S.base) 19 return -1; 20 S.top=S.base; 21 S.stacksize=StackSize; 22 return 0; 23 } 24 SElemtype Push(SqStack &S,SElemtype e) 25 { 26 if(S.top-S.base>=S.stacksize) 27 { 28 S.base=(SElemtype *)realloc(S.base,(StackSize+Sizeincrease)*sizeof(SElemtype)); 29 if(!S.base) 30 return -1; 31 S.top=S.base+S.stacksize; 32 S.stacksize+=Sizeincrease; 33 } 34 *S.top++=e; 35 return 0; 36 } 37 SElemtype Pop(SqStack &S,SElemtype e) 38 { 39 if(S.base==S.top) 40 return -1; 41 e=*--S.top; 42 return 0; 43 } 44 SElemtype DestoryStack(SqStack &S) 45 { 46 if(S.base==S.top) 47 return -1; 48 S.top=S.base; 49 S.stacksize=0; 50 free(S.base); 51 free(S.top); 52 return 0; 53 } 54 SElemtype EmptyStack(SqStack &S) 55 { 56 if(S.top==S.base) 57 return 0; 58 else 59 return -1; 60 } 61 SElemtype ClearStack(SqStack &S) 62 { 63 if(S.top==S.base) 64 return -1; 65 S.top=S.base; 66 S.stacksize=StackSize; 67 return 0; 68 } 69 SElemtype GetTop(SqStack &S,SElemtype &e) 70 { 71 if(S.top==S.base) 72 return -1; 73 e=*(S.top-1); 74 return 0; 75 } 76 SElemtype LengthStack(SqStack S) 77 { 78 if(S.top==S.base) 79 return -1; 80 else 81 return S.top-S.base; 82 } 83 int main() 84 { 85 SqStack S,temp; 86 Initial(S); 87 for(int i=10;i>0;i--) 88 Push(S,i); 89 while(temp.top!=temp.base) 90 printf("%3d",*--temp.top); 91 printf("\n%d",e); 92 printf("\n%d",LengthStack(S)); 93 } 94 95 96 97
评论


浙公网安备 33010602011771号