C Program Circular LinkedList

In this c programming example we will learn Circular LinkedList 

What is Circular LinkedList

circular linked list is a sequence of elements in which every element has a  link to its next element in the sequence and the last element has a link to the first element. 

 

Simple Circular LinkedList in C Program

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

struct node {
   int data;
   
   struct node *next;
   
};

struct node *head = NULL;

struct node *current = NULL;

//insert link at the first location
void add(int data) {
   // Allocate memory for new node;
   struct node *link = (struct node*) malloc(sizeof(struct node));

   link->data = data;
   
   link->next = NULL;

   // If head is empty, create new list
   if(head==NULL) {
       
      head = link;
      
      head->next = link;
      
      return;
   }

   current = head;
   
   // move to the end of the list
   while(current->next != head)
      current = current->next;
   
   // Insert link at the end of the list
   current->next = link;
   
   // Link the last node back to head
   link->next = head;
   
}

//display the list
void readList() {
    
   struct node *ptr = head;

   printf("\n[head] =>");
   
   //start from the beginning
   while(ptr->next != head) {  
       
      printf(" %d =>",ptr->data);
      
      ptr = ptr->next;
   }
   
   printf(" %d =>",ptr->data);
   
   printf(" [head]\n");
}

int main() {
   add(11);
   
   add(16);
   
   add(48);
   
   add(19);
   
   add(32);
   
   add(506); 

   readList();
   
   return 0;
}

 

Output

[head] => 11 => 16 => 48 => 19 => 32 => 506 => [head]