Double Linked List Code
Double Linked List Code
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *prev;
struct node *next;
};
Think of a node as a person holding hands with two other people: one
on the left (prev) and one on the right (next).
c
if (!newNode) {
printf("Memory allocation failed\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
newNode->prev = NULL;
return newNode;
}
We fill the new node (box) with the number (data) and set both its
left (prev) and right (next) neighbors to NULL, meaning the new box
isn’t connected to anything yet.
Finally, it sends back (return) the newly created box (node).
c
This function is used to print the list in forward order, starting from
the first node (head).
o struct node *temp = head: We use a temporary pointer (temp) that
starts at the first node (head).
c
While loop: This loop moves through the chain of nodes, printing the
number (data) in each node until it reaches the end.
o temp = temp->next: After printing the data of the current node, we
move to the next node in the chain.
o The loop stops when we reach the last node, where temp becomes
NULL (no more nodes to print).
This function prints the list in reverse order, starting from the last
node (tail).
c
Similar to the forward print function, this loop prints the data from
the last node to the first by following the prev pointers (going
backwards through the chain).
c
int main() {
int n, data;
struct node *head = NULL, *temp = NULL, *tail = NULL;
The program asks the user how many nodes they want to create
(scanf reads the number and stores it in n).
c
For loop: This loop runs n times (once for each node the user wants
to create).
o For each node, it asks the user to enter a number (data).
o It calls the createNode function to make a new node (box) with that
number.
c
if (head == NULL) {
head = newNode;
} else {
temp->next = newNode;
newNode->prev = temp;
}
temp = newNode;
If block:
o If the list is empty (i.e., head is NULL), the first node we create
becomes the head (the start of the list).
o Otherwise, we connect the new node to the current node (temp) by
setting:
temp->next = newNode: The current node now points to the new
node.
newNode->prev = temp: The new node points back to the current
node.
o Then, we move temp to the new node, so the next iteration can add
the next node after it.
c
tail = temp;
After the loop ends, temp points to the last node. We assign this to
tail so we can print the list in reverse later.
The program prints the list in forward order (starting from head) and
then in reverse order (starting from tail).
c
return 0;
}
This signals the end of the program. The 0 indicates the program ran
successfully.
Summary:
You create a chain of connected boxes (nodes).
Each box holds a number and knows about its neighbors (the
previous and next boxes).
You can print the numbers from the start to the end of the chain
(forward) or from the end to the start (reverse).