- How to define a
struct Nodefor a singly linked list - How to dynamically allocate nodes with
malloc()and check forNULL - How to insert nodes at the head
- How to reverse the list in place using the
prev / current / nextthree-pointer technique - How to traverse and free every node to prevent leaks
Objective & Purpose
Objective: Dynamically allocating memory for a linked list in C and executing a function to reverse it lets you efficiently manage and manipulate a collection of data elements in a flexible, dynamic way. By allocating memory dynamically we can create a linked list that grows or shrinks as needed during program execution. Reversing the list lets us change the order of the elements — useful in many real-world scenarios.
Purpose:
- Efficient memory management — By allocating memory for a dynamic linked list we optimize memory usage, allocating only when needed. This reduces memory waste and improves overall program performance.
- Flexibility in data structure — Linked lists offer a flexible data structure where new elements can be easily added, removed, or rearranged without shifting other elements. Reversing the list adds another dimension of flexibility to the data structure.
💡 Quick Definition: Reversing a singly linked list in place means re-pointing every next pointer so the list runs backwards, using O(1) extra memory — no new nodes, no arrays.
What is Reversing a Linked List?
In a singly linked list, every node points forward to the next one. To reverse the list you must flip every next pointer so it points backward. The head that was at the front ends up at the back, and the tail becomes the new head.
| Pointer | Role |
|---|---|
prev | Tracks the node that will become the new "next" of the current node |
current | The node currently being reversed |
next | Saves current->next before we overwrite it, so we don't lose the rest of the list |
Real-Life Applications
Social Media Feeds
Social media platforms use linked lists to build a feed of posts or updates. Dynamically allocating memory lets new posts be added in constant time. Reversing the list lets users view the feed in chronological or reverse-chronological order.
Task Management Applications
Task managers use linked lists to hold tasks and dynamically allocate memory for new ones. Reversing the list helps users sort tasks based on different priorities or timestamps.
File Management Systems
File managers use linked lists to represent directory structures. Reversing the list can change the order in which files are displayed or retrieved.
Online Shopping Carts
Shopping carts use linked lists to store items added by users. Dynamically allocating memory for new items and reversing the list can optimize the checkout process — for example, showing the most recently added items first.
Complete C Program
Program: Dynamically allocate memory for a linked list and reverse it using a function
#include <stdio.h>
#include <stdlib.h>
/* Define the structure for a node in the linked list */
struct Node
{
int data;
struct Node* next;
};
/* Function to add a new node to the head of the linked list */
void addNode(struct Node** head, int data)
{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL)
{
printf("Memory allocation failed.\n");
return;
}
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
/* Function to reverse the linked list in place */
void reverseList(struct Node** head)
{
struct Node* prev = NULL;
struct Node* current = *head;
struct Node* next = NULL;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
/* Function to print the linked list */
void printList(struct Node* head)
{
struct Node* temp = head;
while (temp != NULL)
{
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
/* Function to free all nodes */
void freeList(struct Node* head)
{
struct Node* temp;
while (head != NULL)
{
temp = head;
head = head->next;
free(temp);
}
}
int main()
{
struct Node* head = NULL;
/* Add nodes to the linked list */
addNode(&head, 1);
addNode(&head, 2);
addNode(&head, 3);
addNode(&head, 4);
printf("Original list: ");
printList(head);
/* Reverse the linked list */
reverseList(&head);
printf("Reversed list: ");
printList(head);
/* Release all allocated nodes */
freeList(head);
return 0;
}
Program Output
Original list: 4 -> 3 -> 2 -> 1 -> NULL
Reversed list: 1 -> 2 -> 3 -> 4 -> NULL
Step-by-Step Explanation
Let's break down this program section by section:
1. Including libraries:
#include <stdio.h>
#include <stdlib.h>
stdio.h provides printf. stdlib.h provides malloc and free.
2. Defining the node structure:
struct Node
{
int data;
struct Node* next;
};
Each node holds an int data and a pointer next to the following node. A list of these nodes is the linked list.
3. Adding a node to the head:
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
The new node is allocated on the heap, given the incoming data, and its next pointer is set to the current head. Then the head is updated to point to the new node. This makes inserts O(1).
4. Reversing the list with three pointers:
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
Each loop iteration saves the next node, points the current node backward to prev, and then advances both pointers. When the loop finishes, prev points to the new head (the old tail).
5. Printing the list:
while (temp != NULL)
{
printf("%d -> ", temp->data);
temp = temp->next;
}
A simple traversal — print each node's data and move to the next — displays the list in readable form.
6. Freeing every node:
while (head != NULL)
{
temp = head;
head = head->next;
free(temp);
}
The key trick: save head to temp, advance head, then free(temp). If you freed first, you'd lose the ability to advance.
🎯 Key Takeaway: Linked-list reversal is a classic pointer-exercise. The prev / current / next pattern appears in many other problems — detecting cycles, finding midpoints, merging lists. Master it once and you'll use it forever.
Frequently Asked Questions
1. Why is addNode adding to the head, not the tail?
Adding to the head is O(1) — no traversal required. Adding to the tail would need a pointer to the last node (or an O(n) traversal each time). For a demo of reversal, head-insertion is the natural pattern.
2. Can I reverse the list recursively?
Yes. A recursive solution reverses the tail first and then adjusts pointers on the way back up the call stack. It's elegant but uses O(n) stack space — the iterative approach here is O(1).
3. Why do I need a separate freeList function?
Every node was allocated with malloc. If you just return from main, the OS reclaims memory — but it's bad practice. In a long-running program, missing frees would leak memory over time.
4. What if the list has only one node?
The algorithm still works: next becomes NULL, current->next becomes prev (NULL), then prev advances to current, current becomes NULL, and the loop ends. The single node becomes the new head.
💡 Tip: Draw the three pointers on paper for a 4-node list and step through the loop manually. It's the fastest way to internalize the algorithm.