The 'prev' pointer concept
What you'll learn: How the addition of a backward-facing pointer transforms a one-way chain into a two-way street for easier data navigation.
The one-way street problem
Imagine you are walking through a gallery where each room has a door leading to the next. In a standard (singly) linked list, you can only move forward. If you realize you missed a beautiful painting in the previous room, you can't just turn around. You would have to leave the building, come back through the front entrance, and walk through every single room again until you reach the one you want.
In programming terms, if you are at Node C and need to access Node B, a singly linked list leaves you stranded. You have no way to look backward.
Enter the 'prev' pointer
A Doubly Linked List solves this by giving every node two hands instead of one. In addition to the next pointer (which points to the following node), we add a prev pointer. This pointer stores the memory address of the node that came right before it.
Think of it like a chain of people holding hands. In a singly linked list, you only put your right hand on the shoulder of the person in front of you. In a doubly linked list, you also reach back with your left hand to hold the shoulder of the person behind you. Now, the chain can be navigated in both directions with ease.
What it looks like in C
To implement this, we simply add one extra pointer to our structure definition:
struct Node {
int data;
struct Node* next; // Points to the next node
struct Node* prev; // Points to the previous node
};
When you create a new node, you now have two responsibilities:
- Set the
nextpointer to the upcoming node. - Set the
prevpointer of that upcoming node back to your current node.
For the very first node in the list (the Head), the prev pointer is set to NULL because nothing comes before it.
Why this matters
This extra pointer makes deleting nodes or traversing backward much faster. You no longer need to keep track of a "previous" variable while looping through your list; the node itself already knows who its neighbor is. While it costs a tiny bit more memory to store that extra address, the ability to move freely in both directions makes your data structure far more flexible.
Key takeaway
The prev pointer is a backward-facing link that allows you to traverse a list in reverse and access preceding nodes instantly.