The C language implements static linked lists

  • 2020-10-31 21:55:54
  • OfStack

This article examples for you to share C language to achieve static linked list specific code, for your reference, specific content is as follows

Notes:

1. k is used to apply for space here, and i traverses the space.
2. Static linked list USES cursor to simulate pointer, divides the fixed allocated memory into standby linked list and standby linked list, and realizes discrete storage when the self-made malloc and free functions are used to apply for the release of spare space.
3, the basic operation and dynamic linked list is actually similar, but one is using p = p- > next1 is the use of i = L[i].cur to achieve pointer back.
4. When the list is initialized, cur of the last space in the list is 0, which means it is a head pointer, and there is no allocated space. The head pointer to 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 a static linked list;
5. Using dynamic linked list thinking, cur members can be regarded as Pointers, and the subscript of which unit is stored in it is equivalent to pointing to which unit.


#include<stdio.h>
#include<stdlib.h>
 
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;
}

Related articles: