Last Updated: 06 October, 2024 5 Mins
Traversal of a doubly linked list means visiting each node in the list sequentially, starting from either the head or the tail. This process allows access to both the previous and next nodes, making it efficient for operations that require bidirectional navigation.
In this article, we will understand how to traversal a doubly linked list in the Farward and Backward direction using the Java programs.
In Doubly Linked List, bidirectional access is very useful for tasks such as inserting or deleting nodes, as it enables easy manipulation of the list structure without the need for additional iterations. Furthermore, traversing a doubly linked list can enhance the performance of algorithms that depend on frequent forward and backward movements through the data.
Class: Node
A Node class represent a single node a doubly linked list, each node contains a data, a reference to the next node, and a reference to the previous node, allowing for bidirectional traversal of the list.
In the forward direction traversal, we start traversing from the head node of the Doubly Linked List and continue visiting the next nodes using the next pointer (address of the next node) of each node untill we reach the last node of the list.
Class: ForwardTraversal
Output
Forward Traversal using Iterative approach: 10 20 30 40 50 Forward Traversal using Recursive approach: 10 20 30 40 50
Time Complexity: O(N), here N present the total number of nodes in the doubly linked list.
Auxiliary Space: O(1)
In Backward Direction Traversal, we start traversing from the last (tail) node of the list and continue traversing the previous nodes using the pointer of previous node of each node till we reach the first node of the list.
Class: BackwardTraversal
Output
Backward Traversal using Iterative approach: 50 40 30 20 10 Backward Traversal using Recursive approach: 50 40 30 20 10
Time Complexity: O(N), here N present the total number of nodes in the doubly linked list.
Auxiliary Space: O(1)
That's all, guys. I hope this article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com