用数组描述的链表 就是静态链表 也叫做游标实现法
#define MAX_SIZE 100
typedef struct Node
{
int value;
int cur;
}Node,StaticList[MAX_SIZE];
数组的第一个和最后一个元素作特殊处理,不存放数据
下标0的元素的cur 存放的是备用链表的第一个节点的下标
下标max-1的元素的cur存放的是第一个有数值的元素下标,相当于单链表的头结点的作用,当链表为空时 则为0
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
#define OK 1
#define ERROR 0
#define ElemType int
typedef struct Node
{
ElemType value;
int cur;
}Node,StaticLinkList[MAX_SIZE];
int initList(StaticLinkList list,int num)
{
for (int i = 1; i <= num; i++)
{
if (i != num)
{
list[i].cur = i + 1;
}
else
{
list[i].cur = 0;
}
list[i].value = rand() % 100 + 1;
}
list[0].value = num;
list[0].cur = num + 1;
list[MAX_SIZE - 1].cur = 1;
return OK;
}
int malloc_ssl(StaticLinkList list)
{
int index = list[0].cur;
if (index)
{
list[0].cur = list[index].cur;
}
return index;
}
void free_ssl(StaticLinkList list, int pos)
{
list[pos].cur = list[0].cur;
list[0].cur = pos;
}
int length(StaticLinkList list)
{
return list[0].value;
}
int insert(StaticLinkList list, int pos, ElemType value)
{
int l = length(list);
if (pos < 1 || pos > l + 1)
{
return ERROR;
}
int k = MAX_SIZE - 1;
for (int i = 0; i < pos - 1; i++)
{
k = list[k].cur;
}
int freeindex = malloc_ssl(list);
if (freeindex)
{
list[freeindex].value = value;
list[freeindex].cur = list[k].cur;
list[k].cur = freeindex;
list[0].value++;
return OK;
}
return ERROR;
}
int del(StaticLinkList list, int pos)
{
int l = length(list);
if (pos < 1 || pos > l + 1)
{
return ERROR;
}
int index = MAX_SIZE - 1;
int last = 0;
for (int i = 0; i < pos; i++)
{
last = index;
index = list[index].cur;
}
list[last].cur = list[index].cur;
free_ssl(list, index);
list[0].value--;
return OK;
}
void dump(StaticLinkList list)
{
int len = list[0].value;
int index = list[MAX_SIZE - 1].cur;
printf("len=%d\n", len);
for (int i = 0; i < len; i++)
{
int value = list[index].value;
printf("index=%d value=%d \n",index,value);
index = list[index].cur;
}
}
int main()
{
StaticLinkList list;
initList(list,5);
dump(list);
insert(list, 1, 99);
printf("insert:\n");
dump(list);
del(list, 2);
printf("del:\n");
dump(list);
return 0;
}