静态链表的C语言代码实现
以下代码仅测试插入操作,删除操作请自行测试
static_link_list.h
#define MAXSIZE 1000
typedef int ElemType;
typedef struct {
ElemType data;
int cur;
}Component, StaticLinkList[MAXSIZE];
bool InitList(StaticLinkList space);
int ListLength(StaticLinkList L);
bool ListInsert(StaticLinkList L, int i, ElemType e);
bool ListInsertOfHead(StaticLinkList L, ElemType e);
bool ListInsertOfTail(StaticLinkList L, ElemType e);
bool ListDelete(StaticLinkList L, int i);
bool ListDeleteOfHead(StaticLinkList L);
bool ListDeleteOfTail(StaticLinkList L);
void ListClean(StaticLinkList L);
void ShowStaticLinkList(StaticLinkList L);
static_link_list.c
#include "static_link_list.h"
#include <stdio.h>
static int Malloc_SSL(StaticLinkList space)
{
int i = space[0].cur;
if (space[0].cur)
space[0].cur = space[i].cur;
return i;
}
static void Free_SSL(StaticLinkList space, int k)
{
space[k].cur = space[0].cur;
space[0].cur = k;
}
bool InitList(StaticLinkList space)
{
int i;
for (i = 0; i < MAXSIZE - 1; i++)
space[i].cur = i + 1;
space[MAXSIZE - 1].cur = 0;
return true;
}
int ListLength(StaticLinkList L)
{
int j = 0;
int i = L[MAXSIZE - 1].cur;
while (i)
{
i = L[i].cur;
j++;
}
return j;
}
bool ListInsert(StaticLinkList L, int i, ElemType e)
{
int j, k, l;
k = MAXSIZE - 1;
if (i < 1 || i > ListLength(L) + 1)
return false;
j = Malloc_SSL(L);
if (j)
{
L[j].data = e;
for (l = 1; l <= i - 1; l++)
k = L[k].cur;
L[j].cur = L[k].cur;
L[k].cur = j;
return true;
}
return false;
}
bool ListInsertOfHead(StaticLinkList L, ElemType e)
{
return ListInsert(L, 1, e);
}
bool ListInsertOfTail(StaticLinkList L, ElemType e)
{
return ListInsert(L, ListLength(L) + 1, e);
}
bool ListDelete(StaticLinkList L, int i)
{
int j, k;
if (i < 1 || i > ListLength(L) + 1)
return false;
k = MAXSIZE - 1;
for (j = 1; j <= i - 1; j++)
k = L[k].cur;
j = L[k].cur;
L[k].cur = L[j].cur;
Free_SSL(L, j);
return true;
}
bool ListDeleteOfHead(StaticLinkList L)
{
return ListDelete(L, 1);
}
bool ListDeleteOfTail(StaticLinkList L)
{
return ListDelete(L, ListLength(L));
}
void ListClean(StaticLinkList L)
{
int i = MAXSIZE - 1;
int j = L[i].cur;
while (j)
{
i = L[j].cur;
Free_SSL(L, i);
}
}
void ShowStaticLinkList(StaticLinkList L)
{
int i = L[MAXSIZE - 1].cur;
while (i)
{
printf("%d ", L[i].data);
i = L[i].cur;
}
printf("\n");
}
test_main.c
#include "static_link_list.h"
#include <stdlib.h>
#include <time.h>
void ListInsertTest()
{
StaticLinkList L;
InitList(L);
srand(time(NULL));
for (int i = 1; i <= 10; i++)
{
int n = rand() % i + 1;
ListInsert(L, n, i);
}
ShowStaticLinkList(L);
}
void ListInsertOfHeadTest()
{
StaticLinkList L;
InitList(L);
for (int i = 1; i <= 10; i++)
{
ListInsertOfHead(L, i);
}
ShowStaticLinkList(L);
}
void ListInsertOfTailTest()
{
StaticLinkList L;
InitList(L);
for (int i = 1; i <= 10; i++)
{
ListInsertOfTail(L, i);
}
ShowStaticLinkList(L);
}
int main()
{
ListInsertTest();
ListInsertOfHeadTest();
ListInsertOfTailTest();
}