The subject requires two stacks to be implemented in an array.
function Interface Definition:
Stack CreateStack( int MaxSize );bool Push( Stack S, ElementType X, int Tag );ElementType Pop( Stack S, int Tag );
This Tag
is the stack number, which takes 1 or 2, MaxSize
the size of the stack array, and the Stack
structure definition as follows:
typedef int Position;struct SNode { ElementType *Data; Position Top1, Top2; int MaxSize;};typedef struct SNode *Stack;
Note: If the stack is full, the Push
function must output "stack fully" and return false; If a stack is empty, the Pop
function must output "stack tag empty" (where tag is the number of the stack) and return error.
Example of a referee test procedure:
#include <stdio.h> #include <stdlib.h> #define ERROR 1e8typedef 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 (); /* Details omitted */void printstack (Stack S, int Tag); /* Details omitted */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;} /* Your code will be embedded here */
Input Sample:
5Push 1 1Pop 2Push 2 11Push 1 2Push 2 12Pop 1Push 2 13Push 2 14Push 1 3Pop 2End
Sample output:
Stack 2 EmptyStack 2 is Empty!Stack FullStack 1 is Full!Pop from Stack 1: 1Pop from Stack 2: 13 12 11
Stack Createstack (intMaxSize) {/*In most case I need to use (if or else) to judge the malloc operation whether success or not*/Stack Sh= (Stack)malloc(sizeof(structSNode)); Sh->data = (ElementType *)malloc(sizeof(int) *MaxSize); Sh->TOP1 =-1; Sh->TOP2 =MaxSize; Sh->maxsize =MaxSize; returnSh;};BOOLPush (Stack S, ElementType x,intTag) { if(S = =NULL)return false; if((S->top1 +1) = = S->Top2) {printf ("Stack full\n"); return false; } if(1==Tag) { + + (s->TOP1); S->data[(S->TOP1)] =x; return true; } Else if(2==Tag) { --(s->TOP2); S->data[(S->TOP2)] =x; return true; } return false;}; ElementType Pop (Stack S,intTag) { if(S = =NULL)returnERROR; if(1==Tag) { if(-1= = S->TOP1) {printf ("Stack%d empty\n", Tag); returnERROR; } return(s->data[(S->TOP1)-- ]); } Else if(2==Tag) { if(S->maxsize = = s->Top2) {printf ("Stack%d empty\n", Tag); returnERROR; } return(s->data[(S->TOP2) + + ]); } returnERROR;};
4-7 implementing two stacks in an array