/* 两栈共享空间 作者:S_hmily 日期:2011年8月31日 编译环境:VC6.0++ 栈1空 S->top1 == -1 栈2空 S->top2 == MaxSize 栈满 S->top1 + 1 == S->top2 */ /************************************************/ #include <stdio.h> /************************************************/ #define MaxSize 20 #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 typedef int ElemType; typedef int Status; typedef struct { ElemType data[MaxSize]; int top1; //栈顶指针1 int top2; //栈顶指针2 }Stack, *pStack; /************************************************/ //初始化 Status InitStack(pStack S) { S->top1 = -1; S->top2 = MaxSize; return OK; } /************************************************/ //压栈 Status Push_Stack(pStack S, ElemType e, int stackNumber) { if (S->top1+1 == S->top2) return ERROR; switch(stackNumber) { case 1: S->data[++S->top1] = e; break; case 2: S->data[--S->top2] = e; break; } return OK; } /************************************************/ //出栈 Status Pop_Stack(pStack S, ElemType *e, int stackNumber) { if (1 == stackNumber) { //栈1空 if (-1 == S->top1) return ERROR; *e = S->data[S->top1--]; } else if (2 == stackNumber) { if (MaxSize == S->top2) return ERROR; *e = S->data[S->top2++]; } return OK; } /************************************************/ //输出栈中所有元素 Status DispStack(pStack S, int stackNumber) { int i; if (1 == stackNumber) { if (-1 == S->top1) return ERROR; printf("栈1中的元素为:"); for (i=0; i<=S->top1; ++i) printf("%d ", S->data[i]); } else if (2 == stackNumber) { if (MaxSize == S->top2) return ERROR; printf("栈2中的元素为:"); for (i=MaxSize-1; i>=S->top2; --i) printf("%d ", S->data[i]); } } /************************************************/ int main(void) { Stack S; ElemType e; InitStack(&S); Push_Stack(&S, 1, 1); Push_Stack(&S, 2, 1); Push_Stack(&S, 3, 1); Push_Stack(&S, 4, 1); Push_Stack(&S, 5, 1); Push_Stack(&S, 6, 1); Pop_Stack(&S, &e, 1); //------------------------------ Push_Stack(&S, 10, 2); Push_Stack(&S, 9, 2); Push_Stack(&S, 8, 2); Push_Stack(&S, 7, 2); DispStack(&S, 1); return 0; } /************************************************/