头文件list.h
#ifndef _LIST_H
#define _LIST_H
#define ElementType int
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
List MakeEmpty();
int IsEmpty(List L);
int IsLast(Position P, List L);
Position Find(ElementType X, List L);
void Insert(ElementType X, List L, Position P);
void Delete(ElementType X, List L);
Position FindPrevious(ElementType X, List L);
void DeleteList(List L);
Position Header(List L);
Position First(List L);
Position Advance(Position P);
ElementType Retrieve(Position P);
void PrintList(List L);
#endif //_LIST_H
实现文件list.c
#include "list.h"
#include <stdio.h>
#include <stdlib.h>
struct Node
{
ElementType Element;
Position Next;
};
List MakeEmpty()
{
List L = malloc(sizeof(struct Node));
if(NULL == L){
perror("malloc for struct Node failed!");
return NULL;
}
L->Next = NULL;
return L;
}
int IsEmpty(List L)
{
return L->Next == NULL;
}
int IsLast(Position P, List L)
{
return P->Next == NULL;
}
Position Find(ElementType X, List L)
{
Position P;
P = L->Next;
while(P != NULL && P->Element != X)
P = P->Next;
return P;
}
/*
* Insert (after legal position P)
* Header implementation assumed.
*/
void Insert(ElementType X, List L, Position P)
{
Position TmpCell;
TmpCell = malloc(sizeof(struct Node));
if(NULL == TmpCell){
perror("Out of space!!!");
return;
}
TmpCell->Element = X;
TmpCell->Next = P->Next;
P->Next = TmpCell;
}
void PrintList(List L)
{
Position P;
P = L->Next;
while(NULL != P){
printf("%d ", P->Element);
P = P->Next;
}
printf("\n");
}
void Delete(ElementType X, List L)
{
Position P, TmpCell;
P = FindPrevious(X, L);
if(!IsLast(P,L)){
TmpCell = P->Next;
P->Next = TmpCell->Next;
free(TmpCell);
}
}
Position FindPrevious(ElementType X, List L)
{
Position P;
P = L;
while(P->Next != NULL && P->Next->Element != X)
P = P->Next;
return P;
}
Position Header(List L)
{
return L;
}
Position First(List L)
{
return L->Next;
}
Position Advance(Position P)
{
// if(NULL != P)
// P = P->Next;
//
// return P;
if(NULL == P)
return NULL;
else
return P->Next;
}
ElementType Retrieve(Position P)
{
return P->Element;
}
void DeleteList(List L)
{
Position P, TmpCell;
P = L;
while(P != NULL){
TmpCell = P;
P = P->Next;
free(TmpCell);
}
L = NULL;
}
测试文件test_list.c
#include "list.h"
#include <stdio.h>
#include <stdlib.h>
int main()
{
List L = MakeEmpty();
if(!IsEmpty(L))
printf("L is empty.\n");
else
printf("L is not empty.\n");
Position P = L;
if(!IsLast(P,L))
printf("P is last.\n");
else
printf("P is not last.\n");
int i;
for(i = 0; i < 10; i++){
Insert(i, L, L);
}
PrintList(L);
if(NULL != Find(5, L))
printf("5 is found\n");
else
printf("5 is not found\n");
P = FindPrevious(5, L);
if(NULL != P)
printf("Previous is %d\n", Retrieve(P));
else
printf("Previous is NULL");
Delete(5, L);
PrintList(L);
P = Find(6, L);
P = Advance(P);
printf("Advance is %d\n", Retrieve(P));
DeleteList(L);
}
参考文献:
Mark Allen Weiss. Data Structures andAlgorithm Analysis in C. Chapter03.