1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Doubly Linked List
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
08Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Doubly Linked List

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
08Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Doubly Linked List

Overview

A Doubly Linked List (DLL) is an evolution of the Singly Linked List. While a singly linked node only knows about the node after it, a doubly linked node maintains two pointers: one pointing to the next node, and one pointing to the previous node.

This addition solves the biggest limitation of a singly linked list: you can now traverse the list backwards just as easily as forwards. More importantly, if you have a reference to a specific node, you can delete it in O(1) time because you immediately have access to its predecessor via the prev pointer. In a singly linked list, even if you know the node to delete, you have to traverse from the head all the way down to find its predecessor (O(N)).

The tradeoff is memory and complexity. Every single node now requires extra memory to store the prev pointer. Additionally, every insertion or deletion operation requires updating four pointers instead of two, increasing the surface area for bugs.

Syntax

Doubly Node Structure and Insertion
java
public class DoublyLinkedList {
    static class Node {
        int data;
        Node prev;
        Node next;
        
        Node(int data) {
            this.data = data;
        }
    }
    
    Node head;
    Node tail; // DLLs often track the tail for O(1) appends
    
    // O(1) Append to end
    public void append(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = tail = newNode;
            return;
        }
        
        // 4 pointer updates required for appending
        tail.next = newNode;   // 1. Old tail points forward to new node
        newNode.prev = tail;   // 2. New node points backward to old tail
        tail = newNode;        // 3. Update tail reference
        // (newNode.next is already null)
    }
    
    // O(1) Deletion if you have the node reference
    public void deleteNode(Node target) {
        if (target == null) return;
        
        if (target.prev != null) {
            target.prev.next = target.next; // Bypass target going forward
        } else {
            head = target.next; // Target was head
        }
        
        if (target.next != null) {
            target.next.prev = target.prev; // Bypass target going backward
        } else {
            tail = target.prev; // Target was tail
        }
    }
}

Common Pitfalls

  • Forgetting to update prev pointers. When inserting a node, developers often remember to update a.next = b, but forget to update b.prev = a. This creates a broken list where forward traversal works, but backward traversal skips nodes or hits NullPointerExceptions.
  • Failing to handle the head and tail edge cases during deletion. If the node being deleted is the head, its prev is null, so target.prev.next = ... will throw an NPE. You must always check if the node is at the boundaries of the list.
  • Memory bloat in cache-heavy applications. Because Java objects have significant memory overhead (object header + data + 2 references), a Doubly Linked List holding primitive ints will use 4-5x more memory than a primitive int[] array.

Interview Questions

What is the main advantage of a Doubly Linked List over a Singly Linked List?

The ability to traverse backwards, and the ability to delete a node in O(1) time if you already have a reference to it (since you immediately know its predecessor via the prev pointer).

How does Java's built-in LinkedList class implement its internal structure?

Java's java.util.LinkedList is implemented as a Doubly Linked List. It maintains both a first (head) and last (tail) pointer, making it implement both the List and Deque (Double Ended Queue) interfaces efficiently.

Can you reverse a Doubly Linked List in O(N) time and O(1) space?

Yes, and it's simpler than a singly linked list. You just traverse the list, and for every node, you swap its prev and next pointers. Finally, you swap the head and tail references of the list itself.

Real-World Example

A web browser's Back and Forward navigation history is a perfect use case for a Doubly Linked List. The current page is a node. Clicking 'Back' moves to node.prev. Clicking 'Forward' moves to node.next. If you visit a new page, you simply overwrite node.next and discard the old forward history.

example
java
class BrowserHistory {
    class PageNode {
        String url;
        PageNode prev, next;
        PageNode(String url) { this.url = url; }
    }
    
    PageNode current;
    
    public void visit(String url) {
        PageNode newPage = new PageNode(url);
        if (current != null) {
            current.next = newPage;
            newPage.prev = current;
        }
        current = newPage; // Move to the new page
    }
    
    public String back() {
        if (current.prev != null) current = current.prev;
        return current.url;
    }
    
    public String forward() {
        if (current.next != null) current = current.next;
        return current.url;
    }
}

Check Your Knowledge

Test your understanding of Doubly Linked List with these quick questions.

Question 1

If you have a reference to a specific middle node in a Doubly Linked List, what is the time complexity to delete it?

Question 2

Which of the following requires more memory per node?

Question 3

What happens if you delete the only node in a Doubly Linked List?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Doubly Linked List

Overview

A Doubly Linked List (DLL) is an evolution of the Singly Linked List. While a singly linked node only knows about the node after it, a doubly linked node maintains two pointers: one pointing to the next node, and one pointing to the previous node.

This addition solves the biggest limitation of a singly linked list: you can now traverse the list backwards just as easily as forwards. More importantly, if you have a reference to a specific node, you can delete it in O(1) time because you immediately have access to its predecessor via the prev pointer. In a singly linked list, even if you know the node to delete, you have to traverse from the head all the way down to find its predecessor (O(N)).

The tradeoff is memory and complexity. Every single node now requires extra memory to store the prev pointer. Additionally, every insertion or deletion operation requires updating four pointers instead of two, increasing the surface area for bugs.

Syntax

Doubly Node Structure and Insertion
java
public class DoublyLinkedList {
    static class Node {
        int data;
        Node prev;
        Node next;
        
        Node(int data) {
            this.data = data;
        }
    }
    
    Node head;
    Node tail; // DLLs often track the tail for O(1) appends
    
    // O(1) Append to end
    public void append(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = tail = newNode;
            return;
        }
        
        // 4 pointer updates required for appending
        tail.next = newNode;   // 1. Old tail points forward to new node
        newNode.prev = tail;   // 2. New node points backward to old tail
        tail = newNode;        // 3. Update tail reference
        // (newNode.next is already null)
    }
    
    // O(1) Deletion if you have the node reference
    public void deleteNode(Node target) {
        if (target == null) return;
        
        if (target.prev != null) {
            target.prev.next = target.next; // Bypass target going forward
        } else {
            head = target.next; // Target was head
        }
        
        if (target.next != null) {
            target.next.prev = target.prev; // Bypass target going backward
        } else {
            tail = target.prev; // Target was tail
        }
    }
}

Common Pitfalls

  • Forgetting to update prev pointers. When inserting a node, developers often remember to update a.next = b, but forget to update b.prev = a. This creates a broken list where forward traversal works, but backward traversal skips nodes or hits NullPointerExceptions.
  • Failing to handle the head and tail edge cases during deletion. If the node being deleted is the head, its prev is null, so target.prev.next = ... will throw an NPE. You must always check if the node is at the boundaries of the list.
  • Memory bloat in cache-heavy applications. Because Java objects have significant memory overhead (object header + data + 2 references), a Doubly Linked List holding primitive ints will use 4-5x more memory than a primitive int[] array.

Interview Questions

What is the main advantage of a Doubly Linked List over a Singly Linked List?

The ability to traverse backwards, and the ability to delete a node in O(1) time if you already have a reference to it (since you immediately know its predecessor via the prev pointer).

How does Java's built-in LinkedList class implement its internal structure?

Java's java.util.LinkedList is implemented as a Doubly Linked List. It maintains both a first (head) and last (tail) pointer, making it implement both the List and Deque (Double Ended Queue) interfaces efficiently.

Can you reverse a Doubly Linked List in O(N) time and O(1) space?

Yes, and it's simpler than a singly linked list. You just traverse the list, and for every node, you swap its prev and next pointers. Finally, you swap the head and tail references of the list itself.

Real-World Example

A web browser's Back and Forward navigation history is a perfect use case for a Doubly Linked List. The current page is a node. Clicking 'Back' moves to node.prev. Clicking 'Forward' moves to node.next. If you visit a new page, you simply overwrite node.next and discard the old forward history.

example
java
class BrowserHistory {
    class PageNode {
        String url;
        PageNode prev, next;
        PageNode(String url) { this.url = url; }
    }
    
    PageNode current;
    
    public void visit(String url) {
        PageNode newPage = new PageNode(url);
        if (current != null) {
            current.next = newPage;
            newPage.prev = current;
        }
        current = newPage; // Move to the new page
    }
    
    public String back() {
        if (current.prev != null) current = current.prev;
        return current.url;
    }
    
    public String forward() {
        if (current.next != null) current = current.next;
        return current.url;
    }
}

Check Your Knowledge

Test your understanding of Doubly Linked List with these quick questions.

Question 1

If you have a reference to a specific middle node in a Doubly Linked List, what is the time complexity to delete it?

Question 2

Which of the following requires more memory per node?

Question 3

What happens if you delete the only node in a Doubly Linked List?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A