Updating the node struct
What you'll learn: How to modify the standard linked list node to support two-way travel by adding a backward-pointing pointer.
The Two-Way Street
Imagine you are walking through a gallery where each room is connected by a door. In a Singly Linked List, those doors are one-way turnstiles. You can move from Room A to Room B, but you can never turn around to see the painting you just passed. To get back, you’d have to leave the building and start all over again from the front door.
A Doubly Linked List changes this by adding a second door. By storing two addresses instead of one, each node knows both who is ahead of it and who is behind it. This turns our "one-way street" into a "two-way highway," allowing us to traverse the list in both directions with ease.
Adding the prev Pointer
In a basic node, we only have the data and a next pointer. To upgrade to a doubly linked list, we introduce a new pointer, usually called prev (short for previous).
Think of it like a person in a line holding hands with two people. Their right hand holds the person in front (next), and their left hand holds the person behind (prev). If you are the first person in line, your left hand holds nothing (NULL). if you are the last, your right hand holds nothing (NULL).
The Code Structure
Here is how we define this new structure in C:
#include <stdio.h>
struct Node {
int data; // The actual information we want to store
struct Node* next; // Pointer to the next node (forward)
struct Node* prev; // Pointer to the previous node (backward)
};
int main() {
// Example of a single node setup
struct Node exampleNode;
exampleNode.data = 42;
exampleNode.next = NULL;
exampleNode.prev = NULL;
printf("Node initialized with data: %d\n", exampleNode.data);
return 0;
}
Why the extra pointer matters
Adding struct Node* prev; might seem like a small change, but it is powerful. It doubles the memory used for pointers, but in exchange, it allows you to delete a node without having to crawl through the entire list from the start to find its predecessor. You simply ask the node, "Who is behind you?" and update that neighbor's next pointer directly.
Key takeaway
A doubly linked list node contains two pointers—next and prev—enabling navigation in both directions at the cost of a little extra memory.