{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# HW2A - p.88 3.21 Write routines to implement two stacks...

This preview shows pages 1–4. Sign up to view the full content.

p.88 3.21 Write routines to implement two stacks using only one array. Your stack routines should not declare an overflow unless every slot in the array is used. #ifndef _Stack_h #define _Stack_h struct StackRecord; typedef struct StackRecord *Stack; int IsEmpty ( Stack S, int Stacknum ); int IsFull ( Stack S ); Stack CreateStack ( int MaxElements ); void Push ( ElementType X, Stack S, int Stacknum ); ElementType Top ( Stack S, int Stacknum ); void Pop ( Stack S, int Stacknum ); #endif /* _Stack_h */ #define MinStackSize ( 5 ) struct StackRecord { int Capacity; int Top1; int Top2; ElementType *Array; } /* The bottom of the first stack is at Array[0] */ /* The bottom of the second stack is at Array[ MaxElement ] */ /* Top1 and Top2 point to the top elements of two stacks respectively */ Top2 Top1 Stack CreateStack ( int MaxElements ) { Stack S; if ( MaxElements < MinStackSize ) return Error(“Stack size is too small”); else { S = malloc( sizeof ( struct StackRecord ) ); /* S points to a stack */ if ( S == Null ) FatalError(“Out of space”); /* create an array for stack elements */ S->Array = malloc( sizeof ( ElementType ) * MaxElements ); if ( S->Array == Null ) FatalError(“Out of space”); S->Capacity = MaxElements; S->Top1 = 1; S->Top2 = MaxElements; /* initialize 2 empty stacks */ return ( S ); } }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
int IsEmpty ( Stack S, int Stacknum ) { if ( Stacknum ==1) /* check stack 1 */ return S->Top1 == 1; else { if ( Stacknum == 2 ) /* check stack 2 */ return S->Top2 == S->Capacity; else return Error(“stack number error”); } } int IsFull ( Stack S ) { return S->Top1+1 == S->Top2; } void Push ( ElementType X, Stack S, int Stacknum ) { if ( IsFull( S ) ) FatalError(“Stack is full”); if ( Stacknum == 1 ) /* push onto stack 1 */ S->Array[++S->Top1] = X; else { if ( Stacknum == 2 ) /* push onto stack 2 */ S->Array[++S->Top2] = X; else Error(“stack number error”); } } ElementType Top ( Stack S, int Stacknum ) { if ( IsEmpty( S, Stacknum ) ) return FatalError(“Stack is empty”); if ( Stacknum == 1 ) /* check stack 1 */ return S->Array[S->Top1]; else { if ( Stacknum == 2 ) /* check stack 2 */ return S->Array[S->Top2]; else return Error(“stack number error”); } }