00:00

Search a specific node in Circular Linked List

Searching for a specific node in a circular linked list can be done by traversing the list starting from the head node. We will continue moving to the next node until we either find the target node or return to the head, indicating that the node is not present in the list.

In this tutorial, we will understand how to search for a specific node in a circular linked list with a given Java program.

Example

Search a node in circular linked list

Java program to find a node in a circular linked list

SearchinCLL.java
// Java program to search for a value in a circular linked list

public class SearchinCLL {
  // Function to search a specific value
  static void search(Node last, int key) {
    // Returns, if the list is empty
    if (last == null) {
      System.out.println("List is an empty.");
      return;
    }

    Node head = last.next;
    Node curr = head;

    // Traverse the list to find the key
    while (curr != last) {
      if (curr.data == key) {
        // Key found
        System.out.println("The key: " + key + " is found.");
        return;
      }
      curr = curr.next;
    }

    // Check the last node
    if (last.data == key) {
      // Key found
      System.out.println("The key: " + key + " is found.");
      return;
    }
    // Key not found
    System.out.println("The key: " + key + " is not found.");
  }

  // Print list
  static void printList(Node last) {
    if (last == null)
      return;

    Node head = last.next;
    while (true) {
      System.out.print(head.data + " ");
      head = head.next;
      if (head == last.next)
        break;
    }
    System.out.println();
  }

  public static void main(String[] args) {
    // Create a circular linked list
    Node head = new Node(50);
    head.next = new Node(20);
    head.next.next = new Node(40);
    head.next.next.next = new Node(10);
    head.next.next.next.next = new Node(30);
    head.next.next.next.next.next = head;

    System.out.print("List value: ");
    printList(head);

    // Passing null as a node and 40 as a key
    search(null, 40);

    // Passing 40 as a key which is present in the list
    search(head, 40);

    // Passing 90 as a key which is not present in the list
    search(head, 90);
  }
}
Output
List value: 20 40 10 30 50
List is an empty.
The key: 40 is found.
The key: 90 is not found.