The C language implements circular linked lists

  • 2020-10-31 21:56:03
  • OfStack

The example of this paper shares the specific code of C language to realize circular linked list for your reference, the specific content is as follows

Notes:

1, loop the linked list to set the tail pointer. Because the tail pointer changes constantly during the operation of the linked list, the pointer to the head pointer is set in the parameter of 1 of some functions. And the end of the linked list to determine if the condition becomes q equal to the tail pointer.
2. Note that the arguments passed need to be addressed
3. The advantages of circular linked list lie in the combination of double linked lists and the simplicity of tail interpolation (first, the new node points to the head node, and then the next field of the tail pointer points to the new node).
4. When creating a linked list, use tail insertion instead of head insertion (because it is difficult to update the tail pointer, so the last tail pointer needs to be updated an extra time), and directly use the head pointer instead of the tail pointer

Code:


#include<stdio.h>
#include<stdlib.h>
 
typedef struct Node
{
 int data;
 struct Node * next;
}Node, *LinkList;
 
LinkList Creat();
void Destroy(LinkList *L);
void Insert(LinkList *L, int val, int index);
void Delete(LinkList *L, int index);
void Traverse(LinkList L);
 
int main()
{
 LinkList L = Creat();
 Traverse(L);
 Insert(&L, 1, 5);
 printf("After inserting is :\n");
 Traverse(L);
 printf("After deleting is :\n");
 Delete(&L, 2);
 Traverse(L);
 Destroy(&L);
 Traverse(L);
}
 
LinkList Creat()
{
 LinkList L = (LinkList)malloc(sizeof(Node));// with L Pointer to a new node, right here L Not to mention the tail pointer 
 int n;
 L->data = -1;
 L->next = L;// The pointer field of the head node points to the head node ,  Attention! Here is the initialization of the tail pointer. 
 printf("Please enter the number you want input:(>5)");
 scanf_s("%d", &n);
 printf("input the number:\n");
 for (int i = 0; i < n; i++)
 {
 LinkList p = (LinkList)malloc(sizeof(Node));
 scanf_s("%d", &p->data);
 p->next = L->next;
 L->next = p;
 L = p;
 }
 return L;// Returns a pointer to the end node 
}
void Destroy(LinkList *L)
{
 LinkList q = (*L)->next->next;
 LinkList p;
 (*L) = (*L)->next;
 while (q != (*L))
 {
 p = q->next;
 free(q);
 q = p;
 }
 (*L)->next = (*L);
}
void Insert(LinkList *L, int val, int index)
{
 LinkList p = (LinkList)malloc(sizeof(Node));
 p->data = val;
 LinkList q = (*L)->next;
 for (int i = 1; q != (*L) && i < index; i++)
 q = q->next;
 p->next = q->next;
 q->next = p;
 if (p == (*L))
 (*L) = p;
}
void Delete(LinkList *L, int index)
{
 LinkList q = (*L)->next, p;
 for (int i = 0; i < index; i++)
 q = q->next;
 p = q->next;
 q->next = p->next;
 free(p);
}
void Traverse(LinkList L)
{
 LinkList q = L->next->next;// That's the initial point 
 while (q != L)
 {
 printf("%d->", q->data);
 q = q->next;
 }
 printf("NULL\n");
}

Related articles: