数据结构_单链表例程


头文件 _List_H

#ifndef _List_H

struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;

List MakeEmpty( List L );
int IsEmpty( List L );
int IsLast( Position P, List L );
Position Find( ElementType X, List L );
void Delete( ElementType X, List L );
Position FindPrevious( ElementType X, List L );
void Insert( ElementType X, List L, Position P );
void DeleteList( List L );
Position Header( List L );
Position First( List L );
Position Advance( Position P );
ElementType Retrieve( Position P );

#endif  /*_List_H*/
/*Place in the implementation file*/
struct Node
{
	ElementType Element;
	Position    Next;
}

详细例程 _List_C

/*Return true if L is empty*/

int IsEmpty( List L )
{
	return L->Next == NULL;
}

/*Return true if P is the last position in List L*/
/*Parameter L is unused in this implementation*/

int IsLast( Position P, List L )
{
	return P->Next == NULL;
}

/*Return Position of X in L;NULL if not found*/
Position Find( ElementType X, List L )
{
	Position P;
	
	P = L->Next;
	while( P != NULL && P->Element != X )
		P = P->Next;

	return P;
}

/*If X is not found, the Next field of returned*
/*Position is NULL*/
/*Assumes a header*/
Position FindPrevious( ElementType X, List L )
{
	Position P;

	P = L;
	while( P->Next != NULL && P->Next->Element != X )
		P = P->Next;

	return P;
}

/*Delete first occurrence of X from a list*/
/*Assume use of a header node*/
void Delete( ElementType X, List L )
{
	Position P, TemCell;

	P = FindPrevious( X, L );
	if( !IsLast( P, L ) )
	{
		TemCell = P->Next;
		P->Next = TemCell->Next;
		free( TemCell );
	}
}

/*Insert (after legal position P)*/
/*Header implementation assumed*/
/*Parameter L is unused in the implementation*/
void Insert( ElementType X, List L, Position P )
{
	Position TmpCell;

	TmpCell = malloc( sizeof( struct Node ) );
	if( TmpCell == NULL )
	{
		printf( "Out of space!!" );
		exit( 1 );
	}

	TmpCell->Element = X;
	TmpCell->Next = P->Next;

	P->Next = TmpCell;
}

/*Make List L empty*/
List MakeEmpty( List L )
{
	Position P, TmpCell;

	P = L->Next;
	L->Next = NULL;
	while( P != NULL )
	{
		TmpCell = P->Next;
		free( P );
		P = TmpCell;
	}

	return L;
}

/* Create a List */
List CreateList( void )
{
	List L;

	L = malloc( sizeof( struct Node ) );
	if( L == NULL )
	{
		printf( "Out of space!!!" );
		exit( 1 );
	}
	L->Next = NULL;
	MakeEmpty( L );
	return L;
}

/*Delete List L*/
void DeleteList( List L )
{
	MakeEmpty( L );
	free( L );
}

Position Header( List L )
{
	return L;
}

Position First( List L )
{
	return L->Next;
}

Position Advance( Position P )
{
	return P->Next;
}

ElementType Retrieve( Position P )
{
	return P->Element;
}



发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注