1.链表的游标实现
①链表的指针实现有两个重要的特点:
数据存储在一组结构体中。每个结构体包含数据以及指向下一个结构体的指针
一个新的结构体可以通过调用malloc而从系统全局内存得到,并可通过调用free而被释放
②游标法
模拟条件1:有一个全局的结构体数组。该数组的任何单元,其数组下标可以用来表示一个地址。
模拟条件2:让CursorSpace数组中的单元带行malloc和free职能。我们保留一个表(freelist),这个表由不在任何表中的单元构成。该表用单元0作为表头。
#include<stdio.h>
#include<stdlib.h>
#define ElementType int
#define SpaceSize 100
typedef int PtrToNode;
typedef PtrToNode Position;
typedef PtrToNote List;
struct Node{
ElementType Element;
Position Next;
};
struct Node CursorSpace[SpaceSize];
Slot | Element | Next |
0 | 1 | |
1 | 2 | |
2 | 3 | |
3 | 4 | |
4 | 5 | |
5 | 6 | |
6 | 7 | |
7 | 8 | |
8 | 9 | |
9 | 10 | |
10 | 0 |
③具体实现
(1) 实现malloc功能:将(表头后面的)第一个元素从freelist删去。
(2)实现free功能:将该单元放在freelist的前端。
static Position CursorAlloc(void){
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;
}
(3)判断一个链表是否为空
(4)测试P是否是链表的末尾的函数
int isEmpty(List L){
return CursorSpace[L].next==0;
}
int isLast(Position P,List L){
return CursorSpace[P].next==L);
}
(5)找到表中值为X的位置
Position Find(ElementType X,List L){
Position P;
P=CursorSpace[L].next;
while(P&&CursorSpace[P].Element!=X){
P=CursorSpace[P].next;
}
return P;
}
(6)对链表进行删除操作
void Delete(ElementType X,List L){
Position P,TmpCell;
P=FindPrevious(X,L);
if(!isLast(P)){
TmpCell=CursorSpace[P].next;
CursorSpace[P].next=CursorSpace[TmpCell].next;
CursorFree(TmpCell);
}
}
(6)对链表进行插入操作
void Insert(ElementType X,Position P,List L){
Position TmpCell;
TmpCell=cursorAlloc();
if(TmpCell==0){
FatalError("Out of Space");
}
CursorSpace[TmpCell].Element=X;
CursorSpace[TmpCell].next=CursorSpace[P].next;
CursorSpace[P].next=TmpCell;
}