大话数据结构-两栈共享空间

  1 #include "stdio.h"    
  2 #include "stdlib.h"   
  3 #include "io.h"  
  4 #include "math.h"  
  5 #include "time.h"
  6 
  7 #define OK 1
  8 #define ERROR 0
  9 #define TRUE 1
 10 #define FALSE 0
 11 #define MAXSIZE 20 /* 存储空间初始分配量 */
 12 
 13 typedef int SElemType;
 14 typedef struct {
 15     SElemType data[MAXSIZE];
 16     int top1;
 17     int top2;
 18 } SqDoubleStack; 
 19 
 20 typedef int Status;
 21 
 22 Status visit(SElemType c){
 23     printf("%d\n",c);
 24     return OK;
 25 }
 26 
 27 Status InitStack(SqDoubleStack *S){
 28     S->top1 = -1;
 29     S->top2 = MAXSIZE;
 30     return OK;
 31 }
 32 
 33 Status ClearStack(SqDoubleStack *S){
 34     S->top1 = -1;
 35     S->top2 = MAXSIZE;
 36     return OK;
 37 }
 38 
 39 Status StackEmpty(SqDoubleStack S){
 40     if(S.top1==-1 && S.top2==MAXSIZE){
 41         return TRUE;
 42     }else{
 43         return FALSE;
 44     }
 45 }
 46 
 47 int StackLength(SqDoubleStack S){
 48     return (S.top1+1) + (MAXSIZE-S.top2);
 49 }
 50 
 51 Status Push(SqDoubleStack *S,SElemType e,int StackNumber){
 52     if((S->top1+1)==S->top2){
 53         return ERROR;
 54     }
 55     if(StackNumber==1){
 56         S->data[++S->top1]=e; 
 57     }
 58     else if(StackNumber==2){
 59         S->data[--S->top2]=e;
 60     }
 61     return OK;
 62 }
 63 
 64 Status Pop(SqDoubleStack *S,SElemType *e,int StackNumber){
 65     if(StackNumber==1){
 66         if(S->top1==-1) return ERROR;
 67         *e = S->data[S->top1--];
 68     }else if(StackNumber==2){
 69         if(S->top2==MAXSIZE) return ERROR;
 70         *e = S->data[S->top2++];
 71     }
 72     return OK;
 73 }
 74 
 75 Status StackTraverse(SqDoubleStack S){
 76     int i;
 77     if(S.top1>-1){
 78         for(i=0;i<=S.top1;i++){
 79             visit(S.data[i]);
 80         }
 81     }
 82     if(S.top2<MAXSIZE){
 83         for(i=S.top2;i<MAXSIZE;i++){
 84             visit(S.data[i]);
 85         }
 86     }
 87     return OK;
 88 }
 89 
 90 int main(void){
 91     int j;
 92         SqDoubleStack s;
 93         int e;
 94         if(InitStack(&s)==OK)
 95         {
 96                 for(j=1;j<=5;j++)
 97                         Push(&s,j,1);
 98                 for(j=MAXSIZE;j>=MAXSIZE-2;j--)
 99                         Push(&s,j,2);
100         }
101 
102         printf("栈中元素依次为:");
103         StackTraverse(s);
104 
105         printf("当前栈中元素有:%d \n",StackLength(s));
106 
107         Pop(&s,&e,2);
108         printf("弹出的栈顶元素 e=%d\n",e);
109         printf("栈空否:%d(1:空 0:否)\n",StackEmpty(s));
110 
111         for(j=6;j<=MAXSIZE-2;j++)
112                 Push(&s,j,1);
113 
114         printf("栈中元素依次为:");
115         StackTraverse(s);
116 
117         printf("栈满否:%d(1:否 0:满)\n",Push(&s,100,1));
118 
119         
120         ClearStack(&s);
121         printf("清空栈后,栈空否:%d(1:空 0:否)\n",StackEmpty(s));
122     return 0;
123 }

 

posted on 2016-04-12 21:54  xxyxpy  阅读(122)  评论(0)    收藏  举报