栈的数组实现

栈的声明

#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 TopAndPop ( Stack S);

#endif 

#define EmptyTOS (-1)
#define MinStackSize (5)

struct StackRecord
{
	int Capacity;
	int TopOfStack;
	ElementType *Array;
}

创建一个空栈

Stack CreateStack( int MaxElements )
{
	Stack S;
	if( MaxElements < MinStackSize )
		Error("Stack size is too 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;
}

释放栈

void DisposeStack( Stack S)
{
	if( S != NULL)
	{
		free( S->Array );
		free( S );
	}
}

检测一个栈是否为空

int IsEmpty( Stack S )
{
	return S->TopOfStack == EmptyTOS;
}

创建一个空栈

void MakeEmpty( Stack S )
{
	 S->TopOfStack == EmptyTOS;
}

Push进栈

void Push( ElementType X,Stack S )
{
	if( IsFull(S))
		Error("Full stack");
	else
		S->Array[ ++S->TopOfArray ] = X;
}

将栈顶返回

ElementType Top( Stack S )
{
	if (!IsEmpty(S))
		return S->Array[ S->TopOfStack ];
	Error("Empty stack");
	return 0;
}

从栈弹出元素

void Pop( Stack S)
{
	if( IsEmpty(S))
		Error("Empty stack");
	else
		S->TopOfStack--;
}
posted @ 2017-01-26 17:31  梁月唯  阅读(232)  评论(0编辑  收藏  举报