一、题目
用一个数组A[ 1....N ]实现两个栈,除非数组的每一个单元都被使用,否则栈例程不能有溢出,注意PUSH和POP操作的时间应为O(1)。
二、解法
对于一个数组,由它的两端作为栈底,栈向数组中间扩展。当数组中每个元素被用到时,栈满。
三、代码
struct Node; typedef Node *ComStack; struct Node { int Capacity; int TopL; int TopR; ElementType *Array; }; ComStack CreatComStack( int MaxElements ); int IsEmpty_L( ComStack S ); int IsEmpty_R( ComStack S ); int IsFull( ComStack S ); void MakeEmpty( ComStack S ); void Push_L( ElementType X, ComStack S ); void Push_R( ElementType X, ComStack S ); ElementType Pop_L( ComStack S ); ElementType Pop_R( ComStack S ); void DisposeComStack( ComStack S ); ComStack CreatComStack( int MaxElements ) { ComStack S; S = (ComStack)malloc( sizeof(struct Node) ); if ( S == NULL ) { printf( "Out of space" ); return NULL; } S->Array = (ElementType *)malloc( sizeof(ElementType) * MaxElements ); if ( S->Array == NULL ) { printf( "Out of space" ); return NULL; } S->Capacity = MaxElements; MakeEmpty(S); return S; } int IsEmpty_L( ComStack S ) { if ( S->TopL == -1 ) return true; else return false; } int IsEmpty_R( ComStack S ) { if ( S->TopR == S->Capacity ) return true; else return false; } int IsFull( ComStack S ) { if ( S->TopL + 1 == S->TopR ) return true; else return false; } void MakeEmpty( ComStack S ) { S->TopL = -1; S->TopR = S->Capacity; // Capacity在数组界外 } void Push_L( ElementType X, ComStack S ) { if ( IsFull(S) ) printf( "Stack is full" ); else { S->TopL++; S->Array[S->TopL] = X; } } void Push_R( ElementType X, ComStack S ) { if ( IsFull(S) ) printf( "Stack is full" ); else { S->TopR--; S->Array[S->TopR] = X; } } ElementType Pop_L( ComStack S ) { ElementType TmpCell; if ( IsEmpty_L(S) ) printf( "Left Stack is empty" ); else { TmpCell = S->Array[S->TopL]; S->TopL--; } return TmpCell; } ElementType Pop_R( ComStack S ) { ElementType TmpCell; if ( IsEmpty_R(S) ) printf( "Right stack is empty" ); else { TmpCell = S->Array[S->TopR]; S->TopR++; } return TmpCell; } void DisposeComStack( ComStack S ) { if ( S != NULL ) { free( S->Array ); free( S ); } }
时间: 2024-08-05 07:08:46