直接上代码:
#include#include #define ERROR 1e8 typedef int ElementType; typedef enum { push, pop, end } Operation; typedef enum { false, true } bool; typedef int Position; struct SNode { ElementType *Data; //虽然是指针类型可以当作数组用 Position Top1, Top2; //实现动态定义数组大小 int MaxSize; }; typedef struct SNode *Stack; Stack CreateStack( int MaxSize ); bool Push( Stack S, ElementType X, int Tag ); ElementType Pop( Stack S, int Tag ); Operation GetOp(); void PrintStack( Stack S, int Tag ); int main() { int N, Tag, X; Stack S; int done = 0; scanf("%d", &N); S = CreateStack(N); while ( !done ) { switch( GetOp() ) { case push: scanf("%d %d", &Tag, &X); if (!Push(S, X, Tag)) printf("Stack %d is Full!n", Tag); break; case pop: scanf("%d", &Tag); X = Pop(S, Tag); if ( X==ERROR ) printf("Stack %d is Empty!n", Tag); break; case end: PrintStack(S, 1); PrintStack(S, 2); done = 1; break; } } return 0; } Operation GetOp() //操作方式 { char ch[10]; scanf("%s",ch); switch (ch[1]) { case('u'):return push; case('o'):return pop; case('n'):return end; } } void PrintStack( Stack S, int Tag ) //输出栈 { if(Tag==1) { printf("Pop from Stack 1:"); while(S->Top1!=-1) {printf("%d ",S->Data[(S->Top1)--]);} printf("n"); } else { printf("Pop from Stack 2:"); while(S->Top2!=S->MaxSize) {printf("%d ",S->Data[(S->Top2)++]);} } } Stack CreateStack( int MaxSize ) //创建栈 { Stack S; S=(Stack)malloc(sizeof(struct SNode)); //S为指针类型,若没有为其分配空间则无法进行下面的分配空间和赋值操作 S->Data=(int*)malloc(4*MaxSize); S->MaxSize=MaxSize; S->Top1=-1; S->Top2=MaxSize; return S; } bool Push( Stack S, ElementType X, int Tag ) //入栈 { if(S->Top2-S->Top1==1) {printf("Stack Fulln"); return false;} if(Tag==1) S->Data[++(S->Top1)]=X; else S->Data[--(S->Top2)]=X; return true; } ElementType Pop( Stack S, int Tag ) //出栈 { if(Tag==1) { if(S->Top1==-1) {printf("Stack 1 Emptyn"); return ERROR;} else return S->Data[(S->Top1)--]; } else { if(S->Top2==S->MaxSize) {printf("Stack 2 Emptyn"); return ERROR;} else return S->Data[(S->Top2)++]; } }



