Bidirectional traversal
What you'll learn: How to navigate a doubly linked list in both forward and backward directions using the two-pointer structure.
The Two-Way Street
In a standard (singly) linked list, moving through nodes is like driving down a one-way street. If you miss your turn, you have to go all the way around the block to start over. A doubly linked list changes this by giving every node two "hands": one reaching for the next node and one reaching for the prev (previous) node.
Bidirectional traversal is the ability to walk this "street" in either direction. This is incredibly useful for features like "Undo" buttons in software or moving back and forth through a web browser's history.
Walking Forward and Backward
To traverse forward, we start at the Head and follow the next pointers until we hit NULL. To traverse backward, we start at the Tail and follow the prev pointers until we hit NULL.
Here is how you implement both directions in C:
#include <stdio.h>
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
void printList(struct Node* head, struct Node* tail) {
struct Node* current;
// Forward traversal
printf("Forward: ");
current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
// Backward traversal
printf("Backward: ");
current = tail;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->prev;
}
printf("NULL\n");
}
Why This Matters
In a singly linked list, if you are at Node C and need to see Node B, you are stuck. You would have to start at the Head and loop through until you find the node whose next pointer matches C.
With bidirectional traversal, you simply ask Node C for its prev pointer. It provides O(1) access to the predecessor, making operations like deleting a node or inserting something before a specific element much faster and more intuitive. While this costs a little extra memory (to store that second pointer), the flexibility of moving in both directions makes data manipulation significantly easier.
Key takeaway
By using next and prev pointers, you can navigate a doubly linked list from start to finish or finish to start with equal ease.