单链表
链表由一系列不必在内存中相邻的结构组成。每一个结构均含有表元素和指向包含该元素后继元的结构的指针,即Next指针。
代码实现如下
List.h
#ifndef _List_H
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
typedef int ElementType;
void InitList(List *L);
int IsEmpty(List L);
int IsLast(Position P, List L);
Position Find(ElementType X, List L);
Position FindPrevious(ElementType X, List L);
void Delete(ElementType X, List L);
void Insert(ElementType X, List L, Position P);
void DeleteList(List L);
void PrintList(List L);
#endif /* _List_H */
struct Node
{
ElementType Element;
Position Next;
};
List.c
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include "List.h"
/* Return true is L is Empty */
int IsEmpty(List L)
{
return L->Next == NULL;
}
/*
* Return true is 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;
}
/*
* Delete first occurence of X from a list
* Assume use of a header node
*/
void Delete(ElementType X,List L)
{
Position P, TmpCell;
P = FindPrevious(X, L);
if(!IsLast(P, L))
{
TmpCell = P->Next;
/* Bypass delete cell */
P->Next = TmpCell->Next;
free(TmpCell);
}
}
/*
* If X is not found, then 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;
}
/*
* Insert (after legal position P)
* Header implementation assumed
* Pasrameter L is unused in this implementation
*/
void Insert(ElementType X, List L, Position P)
{
Position TmpCell;
TmpCell = malloc(sizeof(struct Node));
if(TmpCell == NULL){
printf("Out of space!!!\n");
exit(-1);
}
TmpCell->Element = X;
TmpCell->Next = P->Next;
P->Next = TmpCell;
}
/* Delete List */
void DeleteList(List L)
{
Position P, Tmp;
P = L->Next;
L->Next = NULL;
while(P!=NULL){
Tmp = P->Next;
free(P);
P = Tmp;
}
}
/* Print Elements of List */
void PrintList(List L)
{
Position P;
P = L->Next;
while(P!=NULL)
{
printf("%3d", P->Element);
P = P->Next;
}
}
/* Initialize List */
void InitList(List *L)
{
(*L) = malloc(sizeof(struct Node));
(*L) -> Next = NULL;
}