00:00

Search a specific node in Doubly Linked List

Last updated:

To search a doubly linked list for a value, start at the head and compare each node's data with the value while moving along the next links. The search stops at the first match, or at null if the value is not in the list. It takes O(n) time in the worst case and O(1) when the value is in the first node.

The program below reports the 1-based position of the first node that holds the value, or says that the value was not found.

Java program to find a node in a doubly linked list

Class: Node

Node.java
public class Node {
  int data;   // Data stored in the node
  Node prev;  // Reference to the previous node in the list
  Node next;  // Reference to the next node in the list

  // Constructor to initialize a new node with data
  Node(int new_data) {
    data = new_data;
    prev = null;
    next = null;
  }
}

Class: SearchElementInDLL

SearchElementInDLL.java
// Java Program to search a node in a Doubly Linked List
public class SearchElementInDLL {
  static Node head;

  // Method to insert a node in doubly linked list
  static void insertNode(int data) {
    Node newNode = new Node(data);
    Node last = head;
    if (head == null) {
      head = newNode;
      return;
    }
    while (last.next != null) {
      last = last.next;
    }
    last.next = newNode;
    newNode.prev = last;
  }

  // Method to find the position of an integer
  static void search(int search_element) {
    Node tempNode = head;
    int pos = 0;

    // Traverse the doubly linked list
    while (tempNode != null && tempNode.data != search_element) {
      pos++;
      tempNode = tempNode.next;
    }

    // If the search element is not found in the list
    if (tempNode == null || tempNode.data != search_element) {
      System.out.println("Element: " + search_element + " is not found.");
      return;
    }

    // If the search element is found in the list
    System.out.println("Element: " + search_element
        + " is found at the position: " + (pos + 1));
  }

  // Method to print a list
  static void printList(Node node) {
    while (node != null) {
      System.out.print(node.data + " ");
      node = node.next;
    }
    System.out.println();
  }

  public static void main(String[] args) {
    // Create a doubly linked list
    insertNode(10);
    insertNode(20);
    insertNode(30);
    insertNode(40);
    insertNode(50);

    System.out.print("Doubly linked list:");
    printList(head);

    // Searching element 40
    search(40);

    // Searching element 400
    search(400);
  }
}
Output
Doubly linked list:10 20 30 40 50
Element: 40 is found at the position: 4
Element: 400 is not found.