Circular Linked List

A circular linked list is a type of linked list where the last node of the list points to the first node, forming a cycle. In other words, it’s a linked list that has no end, the tail of the list is connected to the head of the list. Unlike a normal linked list, in a circular linked list, you can traverse the list indefinitely, moving from one node to the next.

Here is an example implementation of a circular linked list in C:

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

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

struct Node* head = NULL;

void insertAtEnd(int data){
  struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
  temp->data = data;
  temp->next = head;

  if(head == NULL){
    head = temp;
    return;
  }

  struct Node* ptr = head;
  while(ptr->next != head){
    ptr = ptr->next;
  }
  ptr->next = temp;
}

void printList(){
  struct Node* ptr = head;
  if(ptr == NULL){
    printf("The list is empty\n");
    return;
  }
  do{
    printf("%d ", ptr->data);
    ptr = ptr->next;
  }while(ptr != head);
  printf("\n");
}

int main(){
  insertAtEnd(1);
  insertAtEnd(2);
  insertAtEnd(3);
  printList();
  return 0;
}

This is just a basic example of a circular linked list, you can add more functionality to it based on your requirements.

Add a Comment

Your email address will not be published. Required fields are marked *