algorithm & data structure

Understanding Doubly Linked Lists: Advantages, Disadvantages and Implementation

kimyounggyun 2024. 4. 17. 09:59

A doubly linked list is a data structure consisting of nodes, where each node contains three fields:

  1. Data: The value or information stored in the node.
  2. Prev: A pointer to the previous node in the list.
  3. Next: A pointer to the next node in the list.

This structure allows traversal in both forward and backward directions, providing greater flexibility compared to a singly linked list.

WIKIPEDIA — Doubly Linked List

Advantages of Doubly Linked Lists

  1. Bidirectional Traversal: Unlike singly linked lists, nodes can be traversed in both directions (forward and backward), making certain operations more convenient and efficient.
  2. Easy Node Deletion: Given access to a specific node, deleting it is straightforward as each node has pointers to both its previous and next nodes.
  3. Complex Operations: More complex data structures like dequeues and caches can be efficiently implemented.

Disadvantages

  1. Increased Memory Usage: Each node requires extra space to store the pointers to the previous and next nodes.
  2. Complexity: Additional bookkeeping is required to maintain the consistency of the prev and next pointers, especially during insertions and deletions.

Time Complexity Analysis

Let \(n\) represent the number of nodes in the list:

  • Insertion at the beginning: \(O(1)\)
  • Append (insertion at the end): \(O(1)\)
  • Deletion of a node (given node pointer): \(O(1)\)
  • Deletion by value (traversal may be needed): \(O(n)\)
  • Search for a value (traversal may be needed): \(O(n)\)
  • Traversal: \(O(n)\)

Doubly Linked List Implementation in C++

Header Implementation

Implementation Details

Example Usage

Conclusion

A doubly linked list is a versatile data structure that supports efficient insertion and deletion operations, making it suitable for various applications like implementing LRU caches. Its bidirectional nature allows for more flexible data management compared to singly linked lists.