00:00

Find length of Doubly Linked List

Last updated:

The length of a doubly linked list is the number of nodes in it. A plain list does not store this number, so it is found by walking the list once and counting the nodes on the way.

Example: the list in the diagram has three nodes, so its length is 3.

Doubly linked list of three nodes with prev and next links; the head's prev and the last node's next are NULL

Algorithm:

  1. Set a counter to 0 and start at the head.
  2. While the current node is not null, add 1 to the counter and move to next.
  3. When the current node becomes null, return the counter. An empty list gives 0.

Example: Find the length of Doubly Linked List in Java

FindLengthOfDLL.java
// Class representing a node in a doubly linked list
class Node {
  public int data;    // Data stored in the node
  public Node prev;   // Reference to the previous node in the list
  public Node next;   // Reference to the next node in the list

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

// Java Program to calculate the length of a Doubly Linked List
public class FindLengthOfDLL {

  // Function to find and print the length of Doubly Linked List
  static void findLength(Node node) {
    int length = 0;
    while (node != null) {
      length++;
      node = node.next;
    }
    System.out.println("The Length of Doubly Linked List is: " + length);
  }

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

    // Find and print the length of a Doubly Linked List
    findLength(head);
  }
}
Output
The Length of Doubly Linked List is: 4

Time Complexity: O(n), where n is the number of nodes; each node is visited once.

Extra Space: O(1)