#单链表之静态链表
先来个空的静态链表:
此表的右上方的小方框就类似与指针了,只是把它作为了游标 cur ;
静态链表中的第一个元素和最后一个元素作为特殊处理,且最后一个元素类似于单链表中的头节点。不断插入元素后,最后一个元素的游标就将存入第一个元素的数组下标
接着来一个已经插入了几个元素的静态链表
再来个删除第一个元素后的静态链表图
#include <stdio.h>
#define maxsize 100
typedef char ElemType;
typedef struct
{
int cur;
ElemType data;
}StaticLink, StaticLinkList[maxsize];
void InitList(StaticLinkList space)
{
int i;
for (i = 0; i < maxsize - 1; i++)
{
space[i].cur = i + 1;
}
space[maxsize - 1].cur = 0; //Similar to the headnode
}
//This is lnegth of static single linked list
int ListLength(StaticLinkList space)
{
int i = space[maxsize - 1].cur;
int j = 0;
while(i)
{
j++;
i = space[i].cur;
}
return j;
}
//Subscript of the allocated space before inserting the element 插入元素前分配空间的下标
int Malloc(StaticLinkList space)
{
int i = space[0].cur;
if (i)
{
space[0].cur = space[i].cur;
}
return i;
}
//The element is inserted before the index
void ListInsert(StaticLinkList space, int index, ElemType key)
{
if (index < 1 || index > ListLength(space)+1)
{
printf("The \'index\' is error !!\n");
return;
}
int j = Malloc(space);
int k = maxsize - 1;
if (j)
{
space[j].data = key;
for (int l = 1; l <= index - 1; l++)
{
k = space[k].cur;
}
space[j].cur = space[k].cur;
space[k].cur = j;
}
return;
}
//Recycling the node labeled 'k' //将下标为k的空闲结点回收到备用链表中
void Free_List(StaticLinkList space, int k)
{
space[k].cur = space[0].cur;
space[0].cur = k;
}
void List_Traverse(StaticLinkList space)
{
int k = maxsize - 1;
while (space[k].cur)
{
k = space[k].cur;
printf("%c", space[k].data);
}
printf("\n");
}
//Delete the flagth data element
void ListDel(StaticLinkList space, int flag)
{
int j, k;
if (flag < 1 || flag > ListLength(space))
{
printf("The \'index\' is error !!\n");
return;
}
k = maxsize - 1;
for (j = 1; j <= flag - 1; j++)
{
k = space[k].cur;
}
j = space[k].cur;
space[k].cur = space[j].cur;
Free_List(space, j);
}
int main()
{
StaticLinkList space;
InitList(space); //Initialize the static single linked list
int n;
printf("Number of inserted elements: ");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
ElemType a;
int m;
printf("Please enter the element`s location of insert: ");
scanf("%d", &m);
getchar();
printf("Please enter the element of insert: ");
scanf("%c", &a);
ListInsert(space, m, a);
}
List_Traverse(space);
int flag;
printf("Please enter the element`s location of deleted: ");
scanf("%d", &flag);
ListDel(space, flag);
List_Traverse(space);
return 0;
}