DouStack:
1 //两栈共享空间 2 #include<iostream> 3 using namespace std; 4 typedef int ElemType; 5 #define MAXSIZE 20 6 7 struct DouStack 8 { 9 ElemType data[MAXSIZE]; 10 int top1; 11 int top2; 12 }; 13 14 void InitStack(DouStack *S) 15 { 16 S->top1 = -1; 17 S->top2 = MAXSIZE; 18 } 19 20 void ClearStack(DouStack *S) 21 { 22 S->top1 = -1; 23 S->top2 = MAXSIZE; 24 } 25 26 bool IsEmpty(DouStack *S) 27 { 28 if(S->top1==-1 && S->top2==MAXSIZE) 29 { 30 cout<<"栈为空!"<<endl; 31 return true; 32 } 33 else 34 { 35 cout<<"栈为空!"<<endl; 36 return false; 37 } 38 } 39 40 int LengthStack(DouStack *S) 41 { 42 return (S->top1+1)+(MAXSIZE-S->top2); 43 } 44 45 void Push(DouStack *S, ElemType *e, int stackNumber) 46 { 47 if(S->top1+1 == S->top2) 48 cout<<"栈已满!"<<endl; 49 if(stackNumber==1) 50 S->data[++S->top1] = *e; 51 else if(stackNumber==2) 52 S->data[--S->top2] = *e; 53 } 54 55 void Pop(DouStack *S, ElemType *e, int stackNumber) 56 { 57 if(stackNumber==1) 58 { 59 if(S->top1==-1) 60 cout<<"栈1已空!"<<endl; 61 *e = S->data[S->top1--]; 62 } 63 else if(stackNumber==2) 64 { 65 if(S->top2==MAXSIZE) 66 cout<<"栈2已空!"<<endl; 67 *e = S->data[S->top2++]; 68 } 69 } 70 71 void PrintStack(DouStack *S) 72 { 73 int i = -1; 74 while(i<S->top1) 75 { 76 cout<<S->data[++i]<<" "; 77 } 78 i = S->top2; 79 while(i<MAXSIZE) 80 { 81 cout<<S->data[i++]<<" "; 82 } 83 cout<<endl; 84 } 85 86 int main() 87 { 88 DouStack S; 89 int e; 90 InitStack(&S); 91 for(int i=1; i<=5; i++) 92 Push(&S, &i, 1); 93 PrintStack(&S); 94 for(int i=MAXSIZE; i>=MAXSIZE-2; i--) 95 Push(&S, &i, 2); 96 PrintStack(&S); 97 cout<<LengthStack(&S)<<endl; 98 99 Pop(&S,&e,2); 100 cout<<"弹出2的栈顶元素为:"<<e<<endl; 101 IsEmpty(&S); 102 Pop(&S,&e,1); 103 cout<<"弹出1的栈顶元素为:"<<e<<endl; 104 for(int i=6; i<=MAXSIZE-2; i++) 105 Push(&S,&i,1); 106 PrintStack(&S); 107 108 ClearStack(&S); 109 cout<<LengthStack(&S)<<endl; 110 IsEmpty(&S); 111 112 return 0; 113 }