SoFunction
Updated on 2025-04-06

C language implements static linked list

This article shares the specific code for implementing static linked lists in C language for your reference. The specific content is as follows

Notes:

1. Here, use k to apply for space and i to traverse the space.
2. Static linked lists use cursors to simulate pointers, divide the fixed allocated memory into two major blocks: alternate linked lists and linked lists. Discrete storage is realized when using homemade malloc and free functions to apply for free space.
3. The basic operations are actually similar to dynamic linked lists, but one is to use p = p->next and the other is to use i = L[i].cur to achieve pointer backward shift.
4. When initializing the linked list, the curs in the last space of the linked list is 0, which means the head pointer and there is no allocated space. The head pointer of the alternate linked list is the first position in the space, and the cur of the last pointer is also 0. 0 also means NULL in static linked lists;
5. Using dynamic linked list thinking, cur members can be regarded as pointers. The subscript of which unit stored in it is equivalent to which unit is pointed to.

#include<>
#include<>
 
typedef struct
{
 int data;
 int cur;
}component, SLinkList[100];
 
int Malloc(SLinkList space)
{
 int i = space[0].cur;
 if (i)
 space[0].cur = space[i].cur;
 return i;
 
}
 
void Free(SLinkList space, int k)
{
 space[k].cur = space[0].cur;
 space[0].cur = k;
}
void Creat(SLinkList L)
{
 int i;
 L[99].cur = 0;
 for (i = 0; i < 98; i++)
 L[i].cur = i + 1;
 L[98].cur = 0;
 
}
 
int ListLength(SLinkList L)
{
 int i = 0, k = L[99].cur;
 while (k)
 {
 k = L[k].cur;
 i++;
 }
 return i;
}
 
void Insert(SLinkList L, int val, int index)
{
 int i = 99, k, n;
 k = Malloc(L);
 if (k)
 {
 L[k].data = val;
 for (n = 1; n < index; n++)
  i = L[i].cur;
 L[k].cur = L[i].cur;
 L[i].cur = k;
 }
}
 
void Traverse(SLinkList L)
{
 int i = L[99].cur;
 while (i)
 {
 printf("%d", L[i].data);
 i = L[i].cur;
 }
}
int main()
{
 SLinkList L;
 Creat(L);
 Insert(L, 1, 1);
 Traverse(L);
 printf("Please enter the number:\n");
 return 0;
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.