Data Structures and Algorithms Tutorials | IT Developer
IT Developer

Data Structures & Algorithms - Circular Linked List Algorithm



Share with a Friend

Circular Linked List

A Circular Linked List is a variation of the linked list in which the last node points to the first node, forming a circle.

There are two main types:

  • Singly Circular Linked List: Each node has a next pointer, and the last node points back to the first.
  • Doubly Circular Linked List: Each node has both next and prev pointers, and the last node’s next points to the first node, and the first node’s prev points to the last.

🔁 Advantages of Circular Linked List

  • Can be traversed from any node (not just the head).
  • Efficient for cyclic operations (e.g., task scheduling, buffering).
  • No need to reset head after traversing the list.

📌 Common Operations

  1. Insert at the beginning
  2. Insert at the end
  3. Delete a node
  4. Traverse the list

 

Example Representation:

[10] -> [20] -> [30] -> back to [10]

Operations on Circular Linked List (Singly)

  1. Insertion
  • At the beginning: Insert a new node before the head and update the last node’s link.
  • At the end: Insert a new node after the last node and update the last node’s link to point to head.
  • At a specific position: Traverse to the specific position and insert the node.
  1. Deletion
  • From the beginning: Delete the head node and update the last node’s link.
  • From the end: Traverse to the second last node and make it point to the head.
  • Specific element: Search and delete a node by value or position.
  1. Traversal
  • Start from the head and keep moving to the next node until you reach the head again.
  1. Search
  • Traverse the list and compare the node data with the key.
  1. Count Nodes
  • Traverse and count the number of nodes until the pointer reaches the head again.

🔁 Circular Nature Reminder

In circular lists:

  • Last node’s next points to the head.
  • Need to handle infinite loops using a condition like while (current != head) after first iteration.

 


1️⃣ Circular Linked List Implementation

✅ 1. Insertion Operations

  • Insertion at the beginning
  • Insertion at the end
  • Insertion at a specific position

 

Insertion in Circular Linked List - C / C++ / Java / Python

🔹 C Program to Insert in Circular Linked List

🔹 C++ Program to Insert in Circular Linked List

🔹 Java Program to Insert in Circular Linked List

🔹 Python Program to Insert in Circular Linked List

 

#include <stdio.h>

#include <stdlib.h>

 

struct Node {

    int data;

    struct Node* next;

};

 

struct Node* head = NULL;

 

// Function to insert at the beginning

void insertAtBeginning(int value) {

    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

    newNode->data = value;

 

    if (head == NULL) {

        head = newNode;

        newNode->next = head;

    } else {

        struct Node* temp = head;

        while (temp->next != head) {

            temp = temp->next;

        }

        newNode->next = head;

        temp->next = newNode;

        head = newNode;

    }

}

 

// Function to insert at the end

void insertAtEnd(int value) {

    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

    newNode->data = value;

 

    if (head == NULL) {

        head = newNode;

        newNode->next = head;

    } else {

        struct Node* temp = head;

        while (temp->next != head) {

            temp = temp->next;

        }

        temp->next = newNode;

        newNode->next = head;

    }

}

 

// Function to insert at a specific position (1-based index)

void insertAtPosition(int value, int pos) {

    if (pos < 1) {

        printf("Invalid position.\n");

        return;

    }

 

    if (pos == 1) {

        insertAtBeginning(value);

        return;

    }

 

    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

    newNode->data = value;

    struct Node* temp = head;

 

    for (int i = 1; i < pos - 1; i++) {

        if (temp->next == head) {

            printf("Position out of range.\n");

            return;

        }

        temp = temp->next;

    }

 

    newNode->next = temp->next;

    temp->next = newNode;

}

 

// Function to display the circular linked list

void display() {

    if (head == NULL) {

        printf("List is empty.\n");

        return;

    }

 

    struct Node* temp = head;

    printf("Circular Linked List: ");

    do {

        printf("%d ", temp->data);

        temp = temp->next;

    } while (temp != head);

    printf("\n");

}

 

// Driver code

int main() {

    insertAtEnd(10);

    insertAtEnd(20);

    insertAtEnd(30);

    display();

 

    insertAtBeginning(5);

    display();

 

    insertAtPosition(15, 3);

    display();

 

    return 0;

}

Output

Circular Linked List: 10 20 30

Circular Linked List: 5 10 20 30

Circular Linked List: 5 10 15 20 30

#include <iostream>

using namespace std;

 

struct Node {

    int data;

    Node* next;

};

 

Node* head = nullptr;

 

// Insert at the beginning

void insertAtBeginning(int value) {

    Node* newNode = new Node();

    newNode->data = value;

 

    if (head == nullptr) {

        newNode->next = newNode;

        head = newNode;

    } else {

        Node* temp = head;

        while (temp->next != head)

            temp = temp->next;

 

        newNode->next = head;

        temp->next = newNode;

        head = newNode;

    }

}

 

// Insert at the end

void insertAtEnd(int value) {

    Node* newNode = new Node();

    newNode->data = value;

 

    if (head == nullptr) {

        newNode->next = newNode;

        head = newNode;

    } else {

        Node* temp = head;

        while (temp->next != head)

            temp = temp->next;

 

        temp->next = newNode;

        newNode->next = head;

    }

}

 

// Insert at a specific position (1-based index)

void insertAtPosition(int value, int position) {

    if (position < 1) {

        cout << "Invalid position.\n";

        return;

    }

 

    if (position == 1) {

        insertAtBeginning(value);

        return;

    }

 

    Node* newNode = new Node();

    newNode->data = value;

 

    Node* temp = head;

    for (int i = 1; i < position - 1; ++i) {

        if (temp->next == head) {

            cout << "Position out of range.\n";

            return;

        }

        temp = temp->next;

    }

 

    newNode->next = temp->next;

    temp->next = newNode;

}

 

// Traverse and print list

void traverse() {

    if (head == nullptr) {

        cout << "List is empty.\n";

        return;

    }

 

    Node* temp = head;

    cout << "Circular Linked List: ";

    do {

        cout << temp->data << " ";

        temp = temp->next;

    } while (temp != head);

    cout << endl;

}

 

int main() {

    insertAtEnd(10);

    insertAtEnd(20);

    insertAtEnd(30);

    traverse();

 

    insertAtBeginning(5);

    traverse();

 

    insertAtPosition(15, 3);

    traverse();

 

    return 0;

}

Output

Circular Linked List: 10 20 30

Circular Linked List: 5 10 20 30

Circular Linked List: 5 10 15 20 30

class CircularLinkedList {

    static class Node {

        int data;

        Node next;

    }

 

    private Node head = null;

 

    // Insert at the beginning

    public void insertAtBeginning(int value) {

        Node newNode = new Node();

        newNode.data = value;

 

        if (head == null) {

            newNode.next = newNode;

            head = newNode;

        } else {

            Node temp = head;

            while (temp.next != head)

                temp = temp.next;

 

            newNode.next = head;

            temp.next = newNode;

            head = newNode;

        }

    }

 

    // Insert at the end

    public void insertAtEnd(int value) {

        Node newNode = new Node();

        newNode.data = value;

 

        if (head == null) {

            newNode.next = newNode;

            head = newNode;

        } else {

            Node temp = head;

            while (temp.next != head)

                temp = temp.next;

 

            temp.next = newNode;

            newNode.next = head;

        }

    }

 

    // Insert at specific position (1-based index)

    public void insertAtPosition(int value, int position) {

        if (position < 1) {

            System.out.println("Invalid position.");

            return;

        }

 

        if (position == 1) {

            insertAtBeginning(value);

            return;

        }

 

        Node newNode = new Node();

        newNode.data = value;

 

        Node temp = head;

        for (int i = 1; i < position - 1; i++) {

            if (temp.next == head) {

                System.out.println("Position out of range.");

                return;

            }

            temp = temp.next;

        }

 

        newNode.next = temp.next;

        temp.next = newNode;

    }

 

    // Traverse the list

    public void traverse() {

        if (head == null) {

            System.out.println("List is empty.");

            return;

        }

 

        Node temp = head;

        System.out.print("Circular Linked List: ");

        do {

            System.out.print(temp.data + " ");

            temp = temp.next;

        } while (temp != head);

        System.out.println();

    }

 

    public static void main(String[] args) {

        CircularLinkedList cll = new CircularLinkedList();

 

        cll.insertAtEnd(10);

        cll.insertAtEnd(20);

        cll.insertAtEnd(30);

        cll.traverse();

 

        cll.insertAtBeginning(5);

        cll.traverse();

 

        cll.insertAtPosition(15, 3);

        cll.traverse();

    }

}

Output

Circular Linked List: 10 20 30

Circular Linked List: 5 10 20 30

Circular Linked List: 5 10 15 20 30

class Node:

    def __init__(self, data):

        self.data = data

        self.next = None

 

class CircularLinkedList:

    def __init__(self):

        self.head = None

 

    # Insert at the beginning

    def insert_at_beginning(self, value):

        new_node = Node(value)

        if not self.head:

            new_node.next = new_node

            self.head = new_node

        else:

            temp = self.head

            while temp.next != self.head:

                temp = temp.next

            new_node.next = self.head

            temp.next = new_node

            self.head = new_node

 

    # Insert at the end

    def insert_at_end(self, value):

        new_node = Node(value)

        if not self.head:

            new_node.next = new_node

            self.head = new_node

        else:

            temp = self.head

            while temp.next != self.head:

                temp = temp.next

            temp.next = new_node

            new_node.next = self.head

 

    # Insert at a specific position (1-based)

    def insert_at_position(self, value, position):

        if position < 1:

            print("Invalid position.")

            return

        if position == 1:

            self.insert_at_beginning(value)

            return

        new_node = Node(value)

        temp = self.head

        for _ in range(position - 2):

            if temp.next == self.head:

                print("Position out of range.")

                return

            temp = temp.next

        new_node.next = temp.next

        temp.next = new_node

 

    # Traverse the list

    def traverse(self):

        if not self.head:

            print("List is empty.")

            return

        print("Circular Linked List:", end=" ")

        temp = self.head

        while True:

            print(temp.data, end=" ")

            temp = temp.next

            if temp == self.head:

                break

        print()

 

# Example usage

cll = CircularLinkedList()

cll.insert_at_end(10)

cll.insert_at_end(20)

cll.insert_at_end(30)

cll.traverse()

 

cll.insert_at_beginning(5)

cll.traverse()

 

cll.insert_at_position(15, 3)

cll.traverse()

Output

Circular Linked List: 10 20 30

Circular Linked List: 5 10 20 30

Circular Linked List: 5 10 15 20 30


✅ 2. Delete Operations

  • Delete from the beginning
  • Delete from the end
  • Delete from a specific position

 

Deletion in Circular Linked List - C / C++ / Java / Python

🔹 C Program to Delete in Circular Linked List

🔹 C++ Program to Delete in Circular Linked List

🔹 Java Program to Delete in Circular Linked List

🔹 Python Program to Delete in Circular Linked List

 

  • #include <stdio.h>

    #include <stdlib.h>

     

    struct Node {

        int data;

        struct Node* next;

    };

     

    struct Node* head = NULL;

     

    // Function to insert a node at the end

    void insertAtEnd(int value) {

        struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

        newNode->data = value;

     

        if (head == NULL) {

            newNode->next = newNode;

            head = newNode;

            return;

        }

     

        struct Node* temp = head;

        while (temp->next != head)

            temp = temp->next;

     

        temp->next = newNode;

        newNode->next = head;

    }

     

    // Function to delete node at the beginning

    void deleteAtBeginning() {

        if (head == NULL) {

            printf("List is empty.\n");

            return;

        }

     

        struct Node* temp = head;

     

        if (head->next == head) {

            free(head);

            head = NULL;

            return;

        }

     

        struct Node* last = head;

        while (last->next != head)

            last = last->next;

     

        head = head->next;

        last->next = head;

        free(temp);

    }

     

    // Function to delete node at the end

    void deleteAtEnd() {

        if (head == NULL) {

            printf("List is empty.\n");

            return;

        }

     

        if (head->next == head) {

            free(head);

            head = NULL;

            return;

        }

     

        struct Node* temp = head;

        while (temp->next->next != head)

            temp = temp->next;

     

        struct Node* last = temp->next;

        temp->next = head;

        free(last);

    }

     

    // Function to delete a node by value

    void deleteByValue(int value) {

        if (head == NULL) {

            printf("List is empty.\n");

            return;

        }

     

        struct Node* temp = head, *prev = NULL;

     

        // If head holds the value

        if (head->data == value) {

            deleteAtBeginning();

            return;

        }

     

        do {

            prev = temp;

            temp = temp->next;

            if (temp->data == value) {

                prev->next = temp->next;

                free(temp);

                return;

            }

        } while (temp != head);

     

        printf("Value not found in the list.\n");

    }

     

    // Function to traverse and print the list

    void traverse() {

        if (head == NULL) {

            printf("List is empty.\n");

            return;

        }

     

        struct Node* temp = head;

        printf("Circular Linked List: ");

        do {

            printf("%d ", temp->data);

            temp = temp->next;

        } while (temp != head);

        printf("\n");

    }

     

    // Main function to test the operations

    int main() {

        insertAtEnd(10);

        insertAtEnd(20);

        insertAtEnd(30);

        insertAtEnd(40);

        traverse();

     

        deleteAtBeginning();

        traverse();

     

        deleteAtEnd();

        traverse();

     

        deleteByValue(20);

        traverse();

     

        deleteByValue(99); // Not present

        traverse();

     

        return 0;

    }

Output


Circular Linked List: 10 20 30 40

Circular Linked List: 20 30 40

Circular Linked List: 20 30

Circular Linked List: 30

Value not found in the list.

Circular Linked List: 30

#include <iostream>

using namespace std;

 

struct Node {

    int data;

    Node* next;

};

 

Node* head = nullptr;

 

// Insert a node at the end

void insertAtEnd(int value) {

    Node* newNode = new Node{value, nullptr};

    if (head == nullptr) {

        newNode->next = newNode;

        head = newNode;

        return;

    }

    Node* temp = head;

    while (temp->next != head) {

        temp = temp->next;

    }

    temp->next = newNode;

    newNode->next = head;

}

 

// Delete node at the beginning

void deleteAtBeginning() {

    if (!head) {

        cout << "List is empty.\n";

        return;

    }

 

    if (head->next == head) {

        delete head;

        head = nullptr;

        return;

    }

 

    Node* temp = head;

    Node* last = head;

 

    while (last->next != head) {

        last = last->next;

    }

 

    head = head->next;

    last->next = head;

    delete temp;

}

 

// Delete node at the end

void deleteAtEnd() {

    if (!head) {

        cout << "List is empty.\n";

        return;

    }

 

    if (head->next == head) {

        delete head;

        head = nullptr;

        return;

    }

 

    Node* temp = head;

    while (temp->next->next != head) {

        temp = temp->next;

    }

 

    Node* last = temp->next;

    temp->next = head;

    delete last;

}

 

// Delete node by value

void deleteByValue(int value) {

    if (!head) {

        cout << "List is empty.\n";

        return;

    }

 

    if (head->data == value) {

        deleteAtBeginning();

        return;

    }

 

    Node* temp = head;

    Node* prev = nullptr;

 

    do {

        prev = temp;

        temp = temp->next;

        if (temp->data == value) {

            prev->next = temp->next;

            delete temp;

            return;

        }

    } while (temp != head);

 

    cout << "Value not found in the list.\n";

}

 

// Display the list

void traverse() {

    if (!head) {

        cout << "List is empty.\n";

        return;

    }

 

    Node* temp = head;

    cout << "Circular Linked List: ";

    do {

        cout << temp->data << " ";

        temp = temp->next;

    } while (temp != head);

    cout << endl;

}

 

// Main function

int main() {

    insertAtEnd(10);

    insertAtEnd(20);

    insertAtEnd(30);

    insertAtEnd(40);

    traverse();

 

    deleteAtBeginning();

    traverse();

 

    deleteAtEnd();

    traverse();

 

    deleteByValue(20);

    traverse();

 

    deleteByValue(99); // Not in list

    traverse();

 

    return 0;

}

Output

Circular Linked List: 10 20 30 40

Circular Linked List: 20 30 40

Circular Linked List: 20 30

Circular Linked List: 30

Value not found in the list.

Circular Linked List: 30

class CircularLinkedList {

    static class Node {

        int data;

        Node next;

 

        Node(int value) {

            data = value;

            next = null;

        }

    }

 

    private Node head = null;

 

    // Insert at the end

    public void insertAtEnd(int value) {

        Node newNode = new Node(value);

        if (head == null) {

            newNode.next = newNode;

            head = newNode;

            return;

        }

 

        Node temp = head;

        while (temp.next != head) {

            temp = temp.next;

        }

 

        temp.next = newNode;

        newNode.next = head;

    }

 

    // Delete at the beginning

    public void deleteAtBeginning() {

        if (head == null) {

            System.out.println("List is empty.");

            return;

        }

 

        if (head.next == head) {

            head = null;

            return;

        }

 

        Node last = head;

        while (last.next != head) {

            last = last.next;

        }

 

        head = head.next;

        last.next = head;

    }

 

    // Delete at the end

    public void deleteAtEnd() {

        if (head == null) {

            System.out.println("List is empty.");

            return;

        }

 

        if (head.next == head) {

            head = null;

            return;

        }

 

        Node temp = head;

        while (temp.next.next != head) {

            temp = temp.next;

        }

 

        temp.next = head;

    }

 

    // Delete node by value

    public void deleteByValue(int value) {

        if (head == null) {

            System.out.println("List is empty.");

            return;

        }

 

        if (head.data == value) {

            deleteAtBeginning();

            return;

        }

 

        Node current = head;

        Node prev = null;

        do {

            prev = current;

            current = current.next;

 

            if (current.data == value) {

                prev.next = current.next;

                return;

            }

        } while (current != head);

 

        System.out.println("Value not found in the list.");

    }

 

    // Display the list

    public void traverse() {

        if (head == null) {

            System.out.println("List is empty.");

            return;

        }

 

        Node temp = head;

        System.out.print("Circular Linked List: ");

        do {

            System.out.print(temp.data + " ");

            temp = temp.next;

        } while (temp != head);

        System.out.println();

    }

 

    // Main method

    public static void main(String[] args) {

        CircularLinkedList cll = new CircularLinkedList();

 

        cll.insertAtEnd(10);

        cll.insertAtEnd(20);

        cll.insertAtEnd(30);

        cll.insertAtEnd(40);

        cll.traverse();

 

        cll.deleteAtBeginning();

        cll.traverse();

 

        cll.deleteAtEnd();

        cll.traverse();

 

        cll.deleteByValue(20);

        cll.traverse();

 

        cll.deleteByValue(99); // Not present

        cll.traverse();

    }

}

Output

Circular Linked List: 10 20 30 40

Circular Linked List: 20 30 40

Circular Linked List: 20 30

Circular Linked List: 30

Value not found in the list.

Circular Linked List: 30

class Node:

    def __init__(self, data):

        self.data = data

        self.next = None

 

class CircularLinkedList:

    def __init__(self):

        self.head = None

 

    def insert_at_end(self, data):

        new_node = Node(data)

        if not self.head:

            new_node.next = new_node

            self.head = new_node

            return

 

        temp = self.head

        while temp.next != self.head:

            temp = temp.next

 

        temp.next = new_node

        new_node.next = self.head

 

    def delete_at_beginning(self):

        if not self.head:

            print("List is empty.")

            return

 

        if self.head.next == self.head:

            self.head = None

            return

 

        last = self.head

        while last.next != self.head:

            last = last.next

 

        self.head = self.head.next

        last.next = self.head

 

    def delete_at_end(self):

        if not self.head:

            print("List is empty.")

            return

 

        if self.head.next == self.head:

            self.head = None

            return

 

        temp = self.head

        while temp.next.next != self.head:

            temp = temp.next

 

        temp.next = self.head

 

    def delete_by_value(self, value):

        if not self.head:

            print("List is empty.")

            return

 

        if self.head.data == value:

            self.delete_at_beginning()

            return

 

        current = self.head

        prev = None

        found = False

 

        while True:

            prev = current

            current = current.next

            if current.data == value:

                prev.next = current.next

                found = True

                break

            if current == self.head:

                break

 

        if not found:

            print("Value not found in the list.")

 

    def traverse(self):

        if not self.head:

            print("List is empty.")

            return

 

        result = []

        temp = self.head

        while True:

            result.append(str(temp.data))

            temp = temp.next

            if temp == self.head:

                break

        print("Circular Linked List:", " -> ".join(result))

 

# Driver Code

if __name__ == "__main__":

    cll = CircularLinkedList()

    cll.insert_at_end(10)

    cll.insert_at_end(20)

    cll.insert_at_end(30)

    cll.insert_at_end(40)

    cll.traverse()

 

    cll.delete_at_beginning()

    cll.traverse()

 

    cll.delete_at_end()

    cll.traverse()

 

    cll.delete_by_value(20)

    cll.traverse()

 

    cll.delete_by_value(99)  # Not present

    cll.traverse()

Output

Circular Linked List: 10 20 30 40

Circular Linked List: 20 30 40

Circular Linked List: 20 30

Circular Linked List: 30

Value not found in the list.

Circular Linked List: 30


✅ 3. Traversal Operations

  • Forward Traversal

Traversal in Circular Linked List - C / C++ / Java / Python

🔹 C Program to Traverse Operations in Circular Linked List

🔹 C++ Program to Traverse Operations in Circular Linked List

🔹 Java Program to Traverse Operations in Circular Linked List

🔹 Python Program to Traverse Operations in Circular Linked List

 

#include <stdio.h>

#include <stdlib.h>

 

// Define the structure for a node

struct Node {

    int data;

    struct Node* next;

};

 

// Function to insert a node at the end of the circular linked list

void insertEnd(struct Node** head_ref, int data) {

    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

    struct Node* temp = *head_ref;

    new_node->data = data;

    new_node->next = *head_ref;

 

    if (*head_ref == NULL) {

        new_node->next = new_node; // Point to itself

        *head_ref = new_node;

        return;

    }

 

    while (temp->next != *head_ref) {

        temp = temp->next;

    }

 

    temp->next = new_node;

}

 

// Function to traverse the circular linked list

void traverse(struct Node* head) {

    struct Node* temp = head;

    if (head == NULL) {

        printf("List is empty.\n");

        return;

    }

 

    printf("Circular Linked List: ");

    do {

        printf("%d ", temp->data);

        temp = temp->next;

    } while (temp != head);

    printf("\n");

}

 

// Driver code

int main() {

    struct Node* head = NULL;

 

    insertEnd(&head, 10);

    insertEnd(&head, 20);

    insertEnd(&head, 30);

    insertEnd(&head, 40);

 

    traverse(head);

 

    return 0;

}

Output

Circular Linked List: 10 20 30 40

#include <iostream>

using namespace std;

 

// Define the Node structure

struct Node {

    int data;

    Node* next;

 

    Node(int val) {

        data = val;

        next = nullptr;

    }

};

 

// Insert node at the end of the circular linked list

void insertEnd(Node*& head, int data) {

    Node* newNode = new Node(data);

    if (head == nullptr) {

        newNode->next = newNode;

        head = newNode;

        return;

    }

 

    Node* temp = head;

    while (temp->next != head) {

        temp = temp->next;

    }

 

    temp->next = newNode;

    newNode->next = head;

}

 

// Traverse and print the circular linked list

void traverse(Node* head) {

    if (head == nullptr) {

        cout << "List is empty." << endl;

        return;

    }

 

    Node* temp = head;

    cout << "Circular Linked List: ";

    do {

        cout << temp->data << " ";

        temp = temp->next;

    } while (temp != head);

    cout << endl;

}

 

// Main function

int main() {

    Node* head = nullptr;

 

    insertEnd(head, 10);

    insertEnd(head, 20);

    insertEnd(head, 30);

    insertEnd(head, 40);

 

    traverse(head);

 

    return 0;

}

Output

Circular Linked List: 10 20 30 40

class CircularLinkedList {

    // Define the Node class

    class Node {

        int data;

        Node next;

 

        Node(int data) {

            this.data = data;

            this.next = null;

        }

    }

 

    Node head = null;

 

    // Insert node at the end of the circular linked list

    public void insertEnd(int data) {

        Node newNode = new Node(data);

 

        if (head == null) {

            newNode.next = newNode;

            head = newNode;

            return;

        }

 

        Node temp = head;

        while (temp.next != head) {

            temp = temp.next;

        }

 

        temp.next = newNode;

        newNode.next = head;

    }

 

    // Traverse and print the circular linked list

    public void traverse() {

        if (head == null) {

            System.out.println("List is empty.");

            return;

        }

 

        Node temp = head;

        System.out.print("Circular Linked List: ");

        do {

            System.out.print(temp.data + " ");

            temp = temp.next;

        } while (temp != head);

        System.out.println();

    }

 

    // Driver Code

    public static void main(String[] args) {

        CircularLinkedList list = new CircularLinkedList();

 

        list.insertEnd(10);

        list.insertEnd(20);

        list.insertEnd(30);

        list.insertEnd(40);

 

        list.traverse();

    }

}

Output

Circular Linked List: 10 20 30 40

class Node:

    def __init__(self, data):

        self.data = data

        self.next = None

 

class CircularLinkedList:

    def __init__(self):

        self.head = None

 

    # Insert node at the end of the circular linked list

    def insert_end(self, data):

        new_node = Node(data)

        if not self.head:

            new_node.next = new_node

            self.head = new_node

            return

 

        temp = self.head

        while temp.next != self.head:

            temp = temp.next

       

        temp.next = new_node

        new_node.next = self.head

 

    # Traverse and print the circular linked list

    def traverse(self):

        if not self.head:

            print("List is empty.")

            return

 

        temp = self.head

        print("Circular Linked List: ", end="")

        while True:

            print(temp.data, end=" ")

            temp = temp.next

            if temp == self.head:

                break

        print()

 

# Driver code

if __name__ == "__main__":

    cll = CircularLinkedList()

 

    cll.insert_end(10)

    cll.insert_end(20)

    cll.insert_end(30)

    cll.insert_end(40)

 

    cll.traverse()

Output

Circular Linked List: 10 20 30 40


✅ 4. Search, Sort, and Reverse in a Circular Linked List

  • C program to perform Search, Sort, and Reverse in a Circular Linked List
  • C++ program to perform Search, Sort, and Reverse in a Circular Linked List
  • Java program to perform Search, Sort, and Reverse in a Circular Linked List
  • Python program to perform Search, Sort, and Reverse in a Circular Linked List

Search, Sort and Reverse in Circular Linked List - C / C++ / Java / Python

🔹 C Program to Search, Sort and Reverse Operations in Circular Linked List

🔹 C++ Program to Search, Sort and Reverse Operations in Circular Linked List

🔹 Java Program to Search, Sort and Reverse Operations in Circular Linked List

🔹 Python Program to Search, Sort and Reverse Operations in Circular Linked List

 

#include <stdio.h>

#include <stdlib.h>

 

// Define the Node structure

struct Node {

    int data;

    struct Node* next;

};

 

// Function to insert a node at the end of the circular linked list

void insertEnd(struct Node** head_ref, int data) {

    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

    struct Node* temp = *head_ref;

    new_node->data = data;

    new_node->next = *head_ref;

 

    if (*head_ref == NULL) {

        new_node->next = new_node; // Point to itself

        *head_ref = new_node;

        return;

    }

 

    while (temp->next != *head_ref) {

        temp = temp->next;

    }

 

    temp->next = new_node;

}

 

// Function to search for a value in the circular linked list

int search(struct Node* head, int key) {

    struct Node* temp = head;

    if (head == NULL) {

        return 0;

    }

 

    do {

        if (temp->data == key) {

            return 1; // Found the key

        }

        temp = temp->next;

    } while (temp != head);

 

    return 0; // Key not found

}

 

// Function to sort the circular linked list using Bubble Sort

void sort(struct Node* head) {

    if (head == NULL) {

        return;

    }

 

    struct Node *i, *j;

    int temp;

    for (i = head; i->next != head; i = i->next) {

        for (j = i->next; j != head; j = j->next) {

            if (i->data > j->data) {

                // Swap data

                temp = i->data;

                i->data = j->data;

                j->data = temp;

            }

        }

    }

}

 

// Function to reverse the circular linked list

void reverse(struct Node** head_ref) {

    if (*head_ref == NULL) {

        return;

    }

 

    struct Node *prev = NULL, *current = *head_ref, *next = NULL;

    struct Node* tail = *head_ref;

 

    // Traverse to the last node (tail)

    while (tail->next != *head_ref) {

        tail = tail->next;

    }

 

    // Reverse the linked list

    do {

        next = current->next;

        current->next = prev;

        prev = current;

        current = next;

    } while (current != *head_ref);

 

    // Set the new head and make the last node point to the new head

    *head_ref = prev;

    tail->next = *head_ref;

}

 

// Function to traverse and print the circular linked list

void traverse(struct Node* head) {

    if (head == NULL) {

        printf("List is empty.\n");

        return;

    }

 

    struct Node* temp = head;

    printf("Circular Linked List: ");

    do {

        printf("%d ", temp->data);

        temp = temp->next;

    } while (temp != head);

    printf("\n");

}

 

// Driver code

int main() {

    struct Node* head = NULL;

 

    // Inserting nodes at the end

    insertEnd(&head, 10);

    insertEnd(&head, 20);

    insertEnd(&head, 30);

    insertEnd(&head, 40);

 

    // Traversing and printing the circular linked list

    traverse(head);

 

    // Search for an element

    int key = 30;

    if (search(head, key)) {

        printf("Element %d found in the list.\n", key);

    } else {

        printf("Element %d not found in the list.\n", key);

    }

 

    // Sort the list

    sort(head);

    printf("Sorted ");

    traverse(head);

 

    // Reverse the list

    reverse(&head);

    printf("Reversed ");

    traverse(head);

 

    return 0;

}

Output

Circular Linked List: 10 20 30 40
Element 30 found in the list.
Sorted Circular Linked List: 10 20 30 40
Reversed Circular Linked List: 40 30 20 10

#include <iostream>

using namespace std;

 

// Define the Node structure

struct Node {

    int data;

    Node* next;

};

 

// Function to insert a node at the end of the circular linked list

void insertEnd(Node*& head, int data) {

    Node* newNode = new Node();

    newNode->data = data;

    if (head == NULL) {

        newNode->next = newNode;

        head = newNode;

        return;

    }

    Node* temp = head;

    while (temp->next != head) {

        temp = temp->next;

    }

    temp->next = newNode;

    newNode->next = head;

}

 

// Function to search for a value in the circular linked list

bool search(Node* head, int key) {

    if (head == NULL) return false;

 

    Node* temp = head;

    do {

        if (temp->data == key) {

            return true;

        }

        temp = temp->next;

    } while (temp != head);

    return false;

}

 

// Function to sort the circular linked list using Bubble Sort

void sort(Node* head) {

    if (head == NULL) return;

 

    Node* i = head;

    Node* j = NULL;

    int temp;

    do {

        j = i->next;

        while (j != head) {

            if (i->data > j->data) {

                // Swap data

                temp = i->data;

                i->data = j->data;

                j->data = temp;

            }

            j = j->next;

        }

        i = i->next;

    } while (i->next != head);

}

 

// Function to reverse the circular linked list

void reverse(Node*& head) {

    if (head == NULL) return;

 

    Node *prev = NULL, *current = head, *next = NULL;

    Node* tail = head;

    while (tail->next != head) {

        tail = tail->next;

    }

 

    do {

        next = current->next;

        current->next = prev;

        prev = current;

        current = next;

    } while (current != head);

 

    head->next = prev;

    head = prev;

    tail->next = head;

}

 

// Function to traverse and print the circular linked list

void traverse(Node* head) {

    if (head == NULL) {

        cout << "List is empty." << endl;

        return;

    }

 

    Node* temp = head;

    cout << "Circular Linked List: ";

    do {

        cout << temp->data << " ";

        temp = temp->next;

    } while (temp != head);

    cout << endl;

}

 

// Driver code

int main() {

    Node* head = NULL;

 

    // Inserting nodes at the end

    insertEnd(head, 10);

    insertEnd(head, 20);

    insertEnd(head, 30);

    insertEnd(head, 40);

 

    // Traversing and printing the circular linked list

    traverse(head);

 

    // Search for an element

    int key = 30;

    if (search(head, key)) {

        cout << "Element " << key << " found in the list." << endl;

    } else {

        cout << "Element " << key << " not found in the list." << endl;

    }

 

    // Sort the list

    sort(head);

    cout << "Sorted ";

    traverse(head);

 

    // Reverse the list

    reverse(head);

    cout << "Reversed ";

    traverse(head);

 

    return 0;

}

Output

Circular Linked List: 10 20 30 40
Element 30 found in the list.
Sorted Circular Linked List: 10 20 30 40
Reversed Circular Linked List: 40 30 20 10

class CircularLinkedList {

 

    // Define the Node class

    static class Node {

        int data;

        Node next;

       

        Node(int data) {

            this.data = data;

            this.next = null;

        }

    }

   

    // Head of the list

    Node head = null;

 

    // Function to insert a node at the end of the circular linked list

    public void insertEnd(int data) {

        Node newNode = new Node(data);

        if (head == null) {

            newNode.next = newNode;

            head = newNode;

            return;

        }

        Node temp = head;

        while (temp.next != head) {

            temp = temp.next;

        }

        temp.next = newNode;

        newNode.next = head;

    }

 

    // Function to search a node by its value

    public boolean search(int key) {

        if (head == null) return false;

 

        Node temp = head;

        do {

            if (temp.data == key) {

                return true;

            }

            temp = temp.next;

        } while (temp != head);

        return false;

    }

 

    // Function to sort the circular linked list using Bubble Sort

    public void sort() {

        if (head == null) return;

 

        Node i = head;

        Node j;

        int temp;

        do {

            j = i.next;

            while (j != head) {

                if (i.data > j.data) {

                    // Swap data

                    temp = i.data;

                    i.data = j.data;

                    j.data = temp;

                }

                j = j.next;

            }

            i = i.next;

        } while (i != head);

    }

 

    // Function to reverse the circular linked list

    public void reverse() {

        if (head == null) return;

 

        Node prev = null, current = head, next = null;

        Node tail = head;

        while (tail.next != head) {

            tail = tail.next;

        }

 

        do {

            next = current.next;

            current.next = prev;

            prev = current;

            current = next;

        } while (current != head);

 

        head.next = prev;

        head = prev;

        tail.next = head;

    }

 

    // Function to traverse and print the circular linked list

    public void traverse() {

        if (head == null) {

            System.out.println("List is empty.");

            return;

        }

 

        Node temp = head;

        System.out.print("Circular Linked List: ");

        do {

            System.out.print(temp.data + " ");

            temp = temp.next;

        } while (temp != head);

        System.out.println();

    }

 

    // Driver code

    public static void main(String[] args) {

        CircularLinkedList list = new CircularLinkedList();

 

        // Insert nodes

        list.insertEnd(10);

        list.insertEnd(20);

        list.insertEnd(30);

        list.insertEnd(40);

 

        // Traverse the list

        list.traverse();

 

        // Search for an element

        int key = 30;

        if (list.search(key)) {

            System.out.println("Element " + key + " found in the list.");

        } else {

            System.out.println("Element " + key + " not found in the list.");

        }

 

        // Sort the list

        list.sort();

        System.out.print("Sorted ");

        list.traverse();

 

        // Reverse the list

        list.reverse();

        System.out.print("Reversed ");

        list.traverse();

    }

}

Output

Circular Linked List: 10 20 30 40
Element 30 found in the list.
Sorted Circular Linked List: 10 20 30 40
Reversed Circular Linked List: 40 30 20 10

class CircularLinkedList:

 

    class Node:

        def __init__(self, data):

            self.data = data

            self.next = None

 

    def __init__(self):

        self.head = None

 

    # Insert at the end of the Circular Linked List

    def insert_end(self, data):

        new_node = self.Node(data)

        if not self.head:

            new_node.next = new_node

            self.head = new_node

            return

        last = self.head

        while last.next != self.head:

            last = last.next

        last.next = new_node

        new_node.next = self.head

 

    # Search for a value in the Circular Linked List

    def search(self, key):

        if not self.head:

            return False

        temp = self.head

        while True:

            if temp.data == key:

                return True

            temp = temp.next

            if temp == self.head:

                break

        return False

 

    # Sort the Circular Linked List (Bubble Sort)

    def sort(self):

        if not self.head:

            return

        temp = self.head

        while True:

            swapped = False

            current = temp

            while current.next != self.head:

                if current.data > current.next.data:

                    current.data, current.next.data = current.next.data, current.data

                    swapped = True

                current = current.next

            if not swapped:

                break

            temp = temp.next

 

    # Reverse the Circular Linked List

    def reverse(self):

        if not self.head:

            return

        prev = None

        current = self.head

        tail = self.head

        while tail.next != self.head:

            tail = tail.next

        while True:

            next_node = current.next

            current.next = prev

            prev = current

            current = next_node

            if current == self.head:

                break

        self.head.next = prev

        self.head = prev

        tail.next = self.head

 

    # Traverse and print the Circular Linked List

    def traverse(self):

        if not self.head:

            print("List is empty.")

            return

        temp = self.head

        print("Circular Linked List: ", end="")

        while True:

            print(temp.data, end=" ")

            temp = temp.next

            if temp == self.head:

                break

        print()

 

# Driver code

if __name__ == "__main__":

    # Create a Circular Linked List

    cll = CircularLinkedList()

 

    # Insert elements

    cll.insert_end(10)

    cll.insert_end(20)

    cll.insert_end(30)

    cll.insert_end(40)

 

    # Traverse the list

    cll.traverse()

 

    # Search for an element

    key = 30

    if cll.search(key):

        print(f"Element {key} found in the list.")

    else:

        print(f"Element {key} not found in the list.")

 

    # Sort the list

    cll.sort()

    print("Sorted list:")

    cll.traverse()

 

    # Reverse the list

    cll.reverse()

    print("Reversed list:")

    cll.traverse()

Output

Circular Linked List: 10 20 30 40
Element 30 found in the list.
Sorted Circular Linked List: 10 20 30 40
Reversed Circular Linked List: 40 30 20 10

Explanation of the Operations:

  1. Insert Operation:
    • We insert nodes at the end of the circular linked list.
  2. Search Operation:
    • The search() function looks for a given value (key) in the list. It returns 1 if the value is found, otherwise 0.
  3. Sort Operation:
    • We use Bubble Sort to sort the elements of the circular linked list in ascending order.
  4. Reverse Operation:
    • The reverse() function reverses the order of the nodes in the circular linked list.
  5. Traverse Operation:
    • We traverse and print the list to check the results after each operation.