栈的链表实现

栈ADT链表实现的类型声明

#ifndef _Stack_h
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;

int IsEmpty( Stack S);
Stack CreateStack ( void );
void DisposeStact ( Stack S );
void MakeEmpty ( Stack S );
void Push ( ElementType X, Stack S);
ElementType Top ( Stack S );
void Pop ( Stack S);

#endif /* _Stack_h */

struct Node
{
	ElementType Element;
	PtrToNode Next;
};

测试栈是否是空栈

int IsEmpty( Stack S )
{
	return S->Next == NULL;
}

创建一个空栈

Stack CreateStack( void )
{
	Stack S;
	S = malloc( sizeof( struct Node ));
	if( S == NULL )
		FatalError("Out of space!!!");
	S->Next == NULL;
	MakeEmpty( S );
	return S;
}
void MakeEmpty( Stack S )
{
	if( S == NULL )
		Error("Must use CreateStack first");
	else
		while( !IsEmpty(S))
			Pop( S );
}

Push进栈

void Push ( ElementType X,Stack S)
{
	PtrToNode TmpCell;
	TmpCell = malloc( sizeof( struct Node));
	if(TmpCell == NULL)
		FataError( "Out of space" );
	else
	{
		TmpCell->Element = x;
		Tmpcell->Next = S->Next;
		S->Next = TmpCell;
	}
}

返回栈顶元素

ElementType Top( Stack S )
{
	if( !IsEmpty(S) )
		return S->Next->Element;
	Error("Empty stack" );
	return 0;
}

Pop栈

void Pop( Stack S )
{
	PtrToNode FirstCell;
	if(IsEmpty(S))
		Error("Empty stack");
	else
	{
		FirstCell = S->Next;
		S->Next = S->Next->Next;
		free(FirstCell);
	}
}
posted @ 2017-01-26 11:30  梁月唯  阅读(369)  评论(0编辑  收藏  举报