871249. Doubly Linked List Traversal

Basic

Doubly Linked List Traversal

Summary

Displaying a doubly linked list means traversing from both ends (beginning and end) of the list. This problem requires implementing an algorithm to print or display nodes in a doubly linked list, where each node has references to its previous and next elements.

Detailed Explanation

The approach to traverse a doubly linked list is straightforward. We will use two pointers, one starting from the beginning of the list (head) and another starting from the end of the list (tail). The head pointer moves towards the tail while the tail pointer moves towards the head. At each step, we print or display the current node.

Here's a step-by-step breakdown:

  1. Initialize two pointers, head and tail, to the beginning and end of the doubly linked list, respectively.
  2. While head is not equal to tail, move the head pointer one step towards the tail by incrementing its reference to the next node, and move the tail pointer one step towards the head by decrementing its reference to the previous node.
  3. At each iteration, print or display the current node (i.e., the node pointed to by head or tail).
  4. Continue until head meets tail, indicating that all nodes in the list have been traversed.

The time complexity for this algorithm is O(n), where n is the number of nodes in the doubly linked list, as we visit each node exactly once. The space complexity is O(1) since we only use a constant amount of space to store the pointers and variables.

Optimized Solutions

Java

View on GeeksforGeeks
public void printDoublyLinkedList(Node head, Node tail) {
    while (head != tail) {
        System.out.println(head.data);
        head = head.next;
        tail = tail.prev;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.