Create A Circular Linked List

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.

Create A Circular Linked List


A Circular linked list can be both singly linked list or doubly linked list.


How to create a Circular linked list?


#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.
Load comments