Circular Linked List Program In C
Circular linked lists are a powerful data structure in C where the last node points back to the first node, creating a loop. They are particularly useful in applications that require continuous traversal, such as buffering and scheduling. There are two main types of circular linked lists: singly circular linked lists, where each node has a single pointer, and doubly circular linked lists, where each node has two pointers. In this article, we will explore both types with detailed examples in C programming. Whether you are preparing for an interview or looking to enhance your coding skills, this guide will provide practical insights and code implementations.
1. Singly Circular Linked List in C
A Singly Circular Linked List is a variation of the traditional singly linked list, where the last node points back to the first node. The example of a singly circular linked list in C is given below
The code implementation in C is given below
#include <stdio.h> #include <stdlib.h> // Structure for a Node // Function to create a new node // Function to insert a node at the end if (head == NULL) { // Function to display the list // Main function head = insertEnd(head, 10); printf(“Singly Circular Linked List: “); return 0; |
Output
Singly Circular Linked List: 10 -> 20 -> 30 -> (Head)
Key Features of Singly Circular Linked List:
- Insertion at the end is efficient since we don’t need to traverse all the way to the last node each time.
- The list loops back on itself, making it circular.
- It doesn’t store a previous pointer (which is what differentiates it from a doubly circular linked list).
2. Doubly Circular Linked List in C
A Doubly Circular Linked List has both the previous and next pointers, where the last node points to the first node and the first node points to the last node. The example of a doubly circular linked list in C is given below
The code implementation for doubly linked circular list in C is given below
#include <stdio.h> #include <stdlib.h> // Structure for a Node // Function to create a new node // Function to insert a node at the end if (head == NULL) { // Function to display the list // Main function head = insertEnd(head, 10); printf(“Doubly Circular Linked List: “); return 0; |
Output:
Doubly Circular Linked List: 10 <-> 20 <-> 30 <-> (Head)
Key Features of Doubly Circular Linked List:
- Each node has a previous and next pointer.
- Both the last node points to the first node and the first node points back to the last node.
- The traversal can be done in both directions (forward and backward).