00:00

Search a specific node in Doubly Linked List

Searching a specific node in a doubly linked list involves traversing through the list while checking each node's value. If the target value is found, we can return the node; otherwise, continue until the end of the list is reached, indicating that the node is not present.

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

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 next node in the list
  Node next;  // Reference to the previous 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.