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 ?


// 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;
    temp = temp->next;

    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.

If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Share on:

NK Coderz is a Computer Science Portal. Here We’re Proving DSA, Free Courses, Leetcode Solutions, Programming Languages, Latest Tech Updates, Blog Posting Etc.

Leave a Comment