栈是一种特殊的结构,具有先进后出的性质。由于栈是一个表,因此任何实现表的方法都能实现栈。
使用数组实现
(1)类型声明
#ifndef _Stack_h
struct StackRecord;
typedef struct StackRecord *Stack;
int IsEmpty( Stack S );
int IsFull( Stack S);
Stack CreateStack( int MaxElements );
void DisposeStack( Stack S);
void MakeEmpty( Stack S);
void Push( ElementType x, Stack S);
ElementType Top( Stack S);
void Pop( Stack S);
ElementType TopAndPop( Stack S );
#endif;
#define EmotyTOS ( -1 )
#define MinStackSize ( 5 )
struct Node
{
int Capacity;
int TopOfStack;
ElementType *Array;
};
(2) 栈的创建
Stack CreateStack(int MaxElements)
{
Stack S;
if(MaxElements <MinStackSize)
Error("Stack size is to small");
S=malloc( sizeof( struct StackRecord ));
if( S=NULL )
FatalError( "out of space!!!" );
S->Array=malloc( sizeof( ElementType ) * MaxElements );
if(S->Array==NULL)
FatalError( "Out of space!!!" );
S->Capacity=MaxElements;
MakeEmpty( S );
return S;
}
(3)释放栈
void DisposeStack( Stack S )
{
if( S != NULL )
{
free( S->Array );
Free( S );
}
}
(4) 检测一个栈是否为空
int IsEmpty( Stack S)
{
return S->TopOfStack == EmptyTOS;
}
(5)创建一个空栈
void MakeEmpty( Stack S)
{
S->TopOfStack=EmptyTOS;
}
(6)进栈
void Push ( ElementType x,Stack S)
{
if( IsFull( S ) )
Error( "FULL stack" );
else
S->Array[ ++S->TopOfStack ] = x;
}
(7)将栈顶返回ElementType Top( Stack S )
{
if( !IsEmpty( S ) )
{
return S->Array[ S->TopOfStack ];
}
Error( "Empty Stack" );
return 0;
}
(8)从栈弹出元素
void pop( Stack S)
{
if( IsEmpty ( S ) )
Error( "Empty stack" );
else S->TopOfStack--;
}