Doubly Linked List Operations
Explore how to implement and manage traversal, insertion at various positions, and deletion operations in doubly linked lists using Python. Understand the role of next and prev references in maintaining list structure and the efficiency of each operation.
By now, you are introduced to the structure of a doubly linked list and how each node stores two references: one to the next node and one to the previous node.
You have already implemented the core linked list operations for singly linked lists, including traversal, insertion, and deletion. The overall ideas behind these operations remain the same in a doubly linked list. However, because each node now stores an additional prev reference, some extra pointer updates are required to keep the structure consistent.
Let’s revisit the three core operations and understand how they work in a doubly linked list, and what changes they entail compared to singly linked lists.
Traversal in a doubly linked list
Traversal in a doubly linked list is primarily the same as traversal in a singly linked list. The process begins at the head node and repeatedly follows the next reference until the end of the list is reached.
As in a singly linked list, a temporary pointer, such as current, is used during traversal so that the head reference remains unchanged. At each step, the data stored in the current node can be processed, such as printing the value or comparing it with a target.
The main difference is that a doubly linked list also supports backward traversal, because each node stores a reference to the previous node.
In summary:
Forward traversal works exactly like it does in a singly linked list by following the
nextreferences.Backward traversal becomes possible by following the
prevreferences.
Backward traversal
To traverse backward in a doubly linked list:
First move to the last node in the list.
Process the data stored in the current node.
Move to the previous node using
current = current.prev.Repeat this process until
currentbecomes NULL, which indicates that the beginning of the list has been passed.
Let’s look at the following interactive visualizer for the doubly linked list traversal.
Python implementation of traversal in a doubly linked list
The following code shows a simple implementation of a doubly linked list and its traversal methods.
Time complexity: Traversal takes
time because each node is visited once. Space complexity: Traversal uses
...