889399. Size of Doubly Linked List

Easy

Size of Doubly Linked List

Summary

The problem is to find the size of a doubly linked list, which is a data structure that has two pointers for each node: one pointing to the previous node and one pointing to the next node. The goal is to write an algorithm that counts the number of nodes in the list.

Detailed Explanation

To solve this problem, we can start at the beginning of the doubly linked list and keep track of how many nodes we've visited until we reach the end. We'll use a variable count to keep track of the size of the list. Here's a step-by-step breakdown of the algorithm:

  1. Start at the head of the doubly linked list.
  2. Initialize the count variable to 0.
  3. While the current node is not null:
    • Increment the count variable by 1.
    • Move to the next node in the list (i.e., the one pointed to by the next pointer).
  4. When we reach the end of the list, return the value of count.

Here's a diagram to illustrate this process:

     +---+
     | A |
     +---+       +---+
           |      /        \
           v     /          \
  +---+   +---+    +---+    +---+
  | B |   | C |    | D |    | E |
  +---+   +---+    +---+    +---+

In this example, the doubly linked list contains nodes A to E. We start at node A and move to each subsequent node until we reach the end of the list.

The time complexity for this algorithm is O(n), where n is the number of nodes in the list, since we visit each node once. The space complexity is O(1) because we only use a constant amount of extra space to store the count variable.

Optimized Solutions

Here are optimized solutions in various programming languages:

Java

View on GeeksforGeeks
public int sizeOfDoublyLinkedList(Node head) {
    Node current = head;
    int count = 0;
    while (current != null) {
        count++;
        current = current.next;
    }
    return count;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.