//Cursor.h
#ifndef _CURSOR_H_
typedef int PtrNode;
typedef PtrNode List;
typedef PtrNode Position;
typedef PtrNode ElementType;
#define SpaceSize 30
struct Node
{
ElementType Element;
Position Next;
};
struct Node CursorSpace[SpaceSize];
void InitializeCursorSpace(int N);
Position CursorAlloc(void);
static void CursorFree(Position P);
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 print_CursorSpace(List L);
#endif
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//Cursor.c
#include<stdio.h>
#include "Cursor.h"
#include<stdlib.h>
void InitializeCursorSpace(int N) //初始化用来装结构体元素的N个空节点
{
int i;
for(i=0;i<N-1;i++)
{
CursorSpace[i].Next=i+1;
}
CursorSpace[i].Next=0;
}
Position CursorAlloc(void)
{
Position P;
P=CursorSpace[0].Next;
CursorSpace[0].Next=CursorSpace[P].Next; //实现malloc功能
return P;
}
static void Cursorfree(Position P)
{
CursorSpace[P].Next=CursorSpace[0].Next; //实现free功能
CursorSpace[0].Next=P;
}
int IsEmpty(List L)
{
return !CursorSpace[L].Next;
}
int IsLast(Position P,List L)
{
return !CursorSpace[P].Next;
}
Position Find(ElementType X,List L)
{
Position p;
p=CursorSpace[L].Next;
while(p&&(CursorSpace[p].Element!=X))
{
p=CursorSpace[p].Next;
}
return p;
}
Position FindPrevious(ElementType X,List L)
{
Position p;
p=L;
while((CursorSpace[p].Next)&&(CursorSpace[CursorSpace[p].Next].Element!=X))
{
p=CursorSpace[p].Next;
}
if(CursorSpace[p].Next==0)
{ //找到了返回p值,否则返回0
return 0;
}
else
{
return p;
}
}
void Delete(ElementType X,List L)
{
Position p,q;
p=FindPrevious(X,L);
if(p==0)
{
printf("Please check your input for correct---X!");
return;
}
else
{
q=CursorSpace[p].Next;
CursorSpace[p].Next=CursorSpace[q].Next;
Cursorfree(q);
}
}
void Insert(ElementType X,List L,Position P) //后插
{
Position q;
q=CursorAlloc();
if(q==0)
{
printf("out of space\n");
}
CursorSpace[q].Element=X;
CursorSpace[q].Next=CursorSpace[P].Next;
CursorSpace[P].Next=q;
}
void print_CursorSpace(List L)
{
List p;
p=L;
while(CursorSpace[p].Next!=0)
{
p=CursorSpace[p].Next;
printf("%d\n",CursorSpace[p].Element);
}
//printf("%d\n",CursorSpace[L].Element);
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//main.c
#include<stdio.h>
#include "Cursor.h"
//void init_cursor(List )
int main(void)
{
int i;
for(i=0;i<SpaceSize-1;i++)
{
CursorSpace[i].Next=i+1;
}
CursorSpace[i].Next=0;
Position L;
L=CursorAlloc(); //获得一个头节点heard
CursorSpace[L].Next=0;
printf("请输入数据存入游标链表中:\n");
int q;
int j=1;
scanf("%d",&q);
if(q!=99)
{
Insert(q,L,L);//后插
}
else
{
return;
}
while(!(q==99)&&(j<10))
{
List p;
p=CursorAlloc();
printf("请输入数据存入游标链表中:\n");
scanf("%d",&q);
if(q!=99)
{
Insert(q,L,L);//后插
}
else
{
printf("------------------------\n");
}
}
print_CursorSpace(L);
}