1 #include<stdio.h> 2 #include<stdlib.h> 3 #define Stack_Size 100 4 #define StackIncrement 10 5 #define OK 1 6 #define TRUE 1 7 #define FALSE 0 8 #define ERROR -1 9 #define OVERFLOW -2 10 typedef int Status; 11 typedef struct 12 { 13 int *base; 14 int *top; 15 int stacksize; 16 }SqStack; 17 Status InitStack(SqStack &S) 18 { 19 S.base=(int *)malloc(Stack_Size*sizeof(int)); 20 if(!S.base) exit(OVERFLOW); 21 S.top=S.base; 22 S.stacksize=Stack_Size; 23 return OK; 24 } 25 Status StackEmpty(SqStack &S) 26 { 27 if(S.top==S.base) 28 return TRUE; 29 return FALSE; 30 } 31 Status StackLength(SqStack S) 32 { 33 return (S.top-S.base); 34 } 35 Status GetTop(SqStack S,int &e) 36 { 37 if(S.top==S.base) return ERROR; 38 e=*(S.top-1); 39 return OK; 40 } 41 Status Push(SqStack &S,int e) 42 { 43 if((S.top-S.base)==S.stacksize) 44 { 45 S.base=(int *)realloc(S.base,(S.stacksize+StackIncrement)*sizeof(int)); 46 if(!S.base) exit(OVERFLOW); 47 S.top=S.base+S.stacksize; 48 S.stacksize+=StackIncrement; 49 } 50 *S.top++=e; 51 return OK; 52 } 53 Status Pop(SqStack &S,int &e) 54 { 55 if(S.top==S.base) return ERROR; 56 e=*--S.top; 57 return OK; 58 } 59 Status PrintSqStack(SqStack S) 60 { 61 int i,length=StackLength(S); 62 puts("堆栈元素为:"); 63 puts("********************"); 64 for(i=0;i<length;i++) 65 printf("%d ",S.base[i]); 66 puts("\n********************"); 67 return OK; 68 } 69 Status main() 70 { 71 int i,e,length; 72 SqStack S; 73 InitStack(S); 74 puts("请输入堆栈长度:"); 75 scanf("%d",&length); 76 puts("请输入堆栈元素:"); 77 for(i=0;i<length;i++) 78 { 79 scanf("%d",&e); 80 Push(S,e); 81 } 82 PrintSqStack(S); 83 puts("请输入要插入的元素:"); 84 scanf("%d",&e); 85 Push(S,e); 86 PrintSqStack(S); 87 puts("删除栈顶元素:"); 88 Pop(S,e); 89 printf("你删除的元素为:%d\n",e); 90 PrintSqStack(S); 91 system("pause"); 92 return OK; 93 }
相关文章: