![]() |
VOOZH | about |
Traversal of Doubly Linked List is one of the fundamental operations, where we traverse or visit each node of the linked list. In this article, we will cover how to traverse all the nodes of a doubly linked list and its implementation.
Examples:
Input:
10 <-> 20 <-> 30 <-> 40
Output:[10, 20, 30, 40]and[40, 30, 20, 10]
Explanation:
- Forward traversal moves from the first node to the last:
[10, 20, 30, 40].- Backward traversal moves from the last node to the first:
[40, 30, 20, 10].Input:
5 <-> 15 <-> 25 <-> 35 <-> 45 <-> 55
Output:[5, 15, 25, 35, 45, 55]and[55, 45, 35, 25, 15, 5]
Explanation:
- Forward traversal follows the order of nodes:
[5, 15, 25, 35, 45, 55].- Backward traversal starts from the last node and moves backward:
[55, 45, 35, 25, 15, 5].Input:
100 <-> 200 <-> 300
Output:[100, 200, 300]and[300, 200, 100]
Explanation:
- Forward traversal reads nodes in order:
[100, 200, 300].- Backward traversal starts at the last node and moves to the first:
[300, 200, 100].
Since each node of Doubly Linked List has pointer to the next node as well as the previous node, we can traverse the linked list in two directions:
In Forward Traversal, we start from the first node, that is the head of the Doubly Linked List and continue visiting the next nodes using the next pointer of each node till we reach the last node of the linked list.
Follow the below steps:
Forward Traversal: 1 2 3
Time Complexity: O(n), where n is the number of nodes in the linked list
Auxiliary Space: O(1)
Follow the below steps:
Forward Traversal: 1 2 3
Time Complexity: O(n), where n is the number of nodes in the linked list
Auxiliary Space: O(n)
In Backward Traversal, we start from the last node, that is the tail of the Doubly Linked List and continue visiting the previous nodes using the prev pointer of each node till we reach the first node of the linked list.
Follow the below steps:
Backward Traversal: 3 2 1
Time Complexity: O(n), where n is the number of nodes in the linked list
Auxiliary Space: O(1)
Follow the below steps:
Backward Traversal: 3 2 1
Time Complexity: O(n), where n is the number of nodes in the linked list
Auxiliary Space: O(n)