Implementation of Circular Link List

Matters needing attention:

  1. Loop list sets tail pointer. Since the tail pointer will change constantly during the operation of the linked list, the pointer to the head pointer is set in the shape parameters of some functions. And the end of the list to determine whether q equals the tail pointer.
  2. Note that the passed arguments need to be addressed
  3. The advantages of circular linked list lie in the merging of double linked list and the simplicity of tail insertion (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 linked lists, tail insertion is used instead of head insertion (because it is difficult to update the tail pointer, so that the last tail pointer needs to be updated once more). Head insertion is used directly to establish the head pointer, not the tail pointer.
 
#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));//Use the L pointer to point to the new node, where L is not the end 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;//A pointer to return the endpoint
}
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 head of state node.
	while (q != L)
	{
		printf("%d->", q->data);
		q = q->next;
	}
	printf("NULL\n");
}

Posted by gardan06 on Tue, 08 Oct 2019 16:03:49 -0700