#include<stdio.h>
#include<stdlib.h>
#define SpaceSize 20
typedef int PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
typedef PtrToNode ElementType;
struct Node
{
ElementType Element;
Position Next;
};
struct Node CursorSpace[SpaceSize];
void Init();
List MakeEmpty(List L);
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);
void Insert(ElementType x,List L,Position P);
void DeleteList(List);
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;
}
void Init()
{
int i;
for(i=0;i<SpaceSize;i++)
CursorSpace[i].Next=i+1;
CursorSpace[i-1].Next=0;
}
int IsEmpty(List L)
{
return CursorSpace[L].Next==0;
}
int IsLast(Position P,List L)
{
return CursorSpace[P].Next==0;
}
Position Find(ElementType x,List L)
{
Position P;
P=CursorSpace[L].Next;
while(P && CursorSpace[P].Element!=x)
{
P=CursorSpace[P].Next;
printf("P=%d ",P);
}
return P;
}
/*int IsLast(const Position P,const List L)
{
Position q;
q=CursorSpace[L].Next;
while(q && q!=P)
{
q=CursorSpace[q].Next;
}
return q;
}*/
void Delete(ElementType x,List L)
{
Position P,q,TmpCell;
P=CursorSpace[L].Next;
if(P && CursorSpace[P].Element!=x)
{
q=CursorSpace[P].Next;
while(q && CursorSpace[q].Element!=x)
{
P=q;
q=CursorSpace[q].Next;
}
}
if(!IsLast(P,L))
{
TmpCell=CursorSpace[P].Next;
CursorSpace[P].Next=CursorSpace[TmpCell].Next;
CursorFree(TmpCell);
}
}
void Insert(ElementType x,List L,Position P)
{
Position TmpCell;
TmpCell=CursorAlloc();
if(TmpCell==0)
printf("out of space");
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;
}
}
void print(List L)
{
Position P;
P=CursorSpace[L].Next;
while(P)
{
printf("%d ",CursorSpace[P].Element);
P=CursorSpace[P].Next;
}
printf("\n");
}
void main()
{
Position P,L;
Init();
L=CursorAlloc();
printf("L=%d \n",L);
CursorSpace[L].Next=0;
P=L;
print(L);
int i;
for(i=0;i<9;i++)
{
Insert(i,L,P);
//print(L);
P=CursorSpace[P].Next;
}
print(L);
P=Find(5,L);
printf("Find(5,L)=%d \n",P);
P=Find(0,L);
printf("Find(0,L)=%d \n",P);
Delete(5,L);
print(L);
}