Create A Circular Linked List
What is a circular linked list?
A Circular linked list is a linked list in which the last node points to the head node and not the NULL value.
A Circular linked list can be both singly linked list or doubly linked list.
How to create a Circular linked list?
// creating a Circular Linked list
//node contain int data and next pointer of struct node data type
struct node *next;
//allocating memory in heap
struct node *head = malloc(sizeof(struct node));
struct node *middle = malloc(sizeof(struct node));
struct node *last = malloc(sizeof(struct node));
//assigning value to each node
head->data = 10;
middle->data = 20;
last->data = 30;
//linking the nodes
last->next = head;
//printing the linked list
struct node *temp = head;
temp = temp->next;
- Creating the structure of node which contains data and a pointer.
- Then we are creating three different pointers which points to node and allocating heap memory for the node by using malloc function.
- After this assigning the data values and conecting each node with the next pointer.
- The last node next points to head node.
- For printing we are using another temp pointer, temp basically traverse in do while loop from one node to another node and print the value until it reach to the head node.