list.h
#ifndef _LIST_H_
#define _LIST_H_
#define SpaceSize 100
typedef int PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
typedef int ElementType;
int IsEmpty(const List L);
int IsLast(const Position P,const List L);
Position Find(ElementType X, const List L);
void Delete(ElementType X, List L);
Position FindPrevious(ElementType X, const List L);
void Insert(ElementType X, List L, Position P);
void DeleteList(List L);
ElementType Retrieve(const Position P);
#endif
list.c
#include<stdio.h>
#include<stdlib.h>
#include"list.h"
struct Node
{
ElementType Element;
Position Next;
};
struct Node CursorSpace[SpaceSize];
static Position CursorAlloc()
{
Position P;
P = CursorSpace[0].Next;
CursorSpace[0].Next = CursorSpace[P].Next;
return P;
}
static void CursorFree(Position P)
{
CursorSpace[P].Next = CursorSpace[0].Next;
CursorSpace[0].Next = P;
}
int IsEmpty(const List L)
{
return CursorSpace[L].Next == 0;
}
int IsLast(const Position P, const List L)
{
return CursorSpace[P].Next == 0;
}
Position Find(ElementType X, const List L)
{
Position P;
P = CursorSpace[L].Next;
while (P && CursorSpace[P].Element!= X)
P = CursorSpace[P].Next;
return P;
}
void Delete(ElementType X, List L)
{
Position P, TmpCell;
P = FindPrevious(X, L);
while (!IsLast(P, L))
{
TmpCell = CursorSpace[P].Next;
CursorSpace[P].Next = CursorSpace[TmpCell].Next;
CursorFree(TmpCell);
}
}
Position FindPrevious(ElementType X, const List L)
{
Position P = L;
Position N = CursorSpace[P].Next;
while (N != 0 &&CursorSpace[N].Element!=X )
{
P = CursorSpace[P].Next;
N = CursorSpace[P].Next;
}
return P;
}
void Insert(ElementType X, List L, Position P)
{
Position TmpCell;
TmpCell = CursorAlloc();
if (TmpCell == 0)
{
printf("FAILURE!\n");
exit(EXIT_FAILURE);
}
CursorSpace[TmpCell].Element = X;
CursorSpace[TmpCell].Next = CursorSpace[P].Next;
CursorSpace[P].Next = TmpCell;
}
void DeleteList(List L)
{
Position P, Tmp;
P = CursorSpace[L].Next;
CursorSpace[L].Next = 0;
while (P)
{
Tmp = CursorSpace[P].Next;
CursorFree(P);
P = Tmp;
}
}
ElementType Retrieve(const Position P)
{
if (P != 0)
return CursorSpace[P].Element;
printf("ERROR!\n");
return 0;
}