00:00

Search a specific node in Circular Linked List

Last updated:

To search a circular linked list, start at the first node and compare each node's value with the key while moving along the ring. The search ends either at a match or when it has gone all the way round; since every node has then been checked once, the key is not in the list. The worst case is O(n), the best case O(1).

The program below keeps a reference to the last node, so the first node is last.next.

Example

Circular linked list 75, 20, 48, 16, 37: searching for 16 gives FOUND, searching for 65 gives NOT FOUND

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 {
  static class Node {
    int data;
    Node next;

    Node(int data) {
      this.data = data;
    }
  }

  // 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 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;

    // search() and printList() expect a reference to the last node
    Node last = head.next.next.next.next;

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

    // Passing null (an empty list) and 40 as a key
    search(null, 40);

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

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