Create A Circular Linked List In C

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 In C ?

#include<stdio.h>
#include<stdlib.h>

// creating a Circular Linked list 
int main(){

//node contain int data and next pointer of struct node data type
struct node{
    int data;
    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
head->next= middle;
middle->next= last;
last->next = head;

//printing the linked list
struct node *temp = head;
do{
    printf("%d",temp->data);
    temp = temp->next;
}while(temp!=head);

    return 0;
}

In the above code, we are doing following things:

  1. Creating the structure of node which contains data and a pointer.
  2. Then we are creating three different pointers which points to node and allocating heap memory for the node by using malloc function.
  3. After this assigning the data values and conecting each node with the next pointer.
  4. The last node next points to head node.
  5. 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.
Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment