C Program: Dynamic Linked List & Reverse
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Dynamically Allocate Memory for a Linked List and Reverse It

📑 On this page:
  • Objective & Purpose
  • What is Reversing a Linked List?
  • Real-Life Applications
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to define a struct Node for a singly linked list
  • How to dynamically allocate nodes with malloc() and check for NULL
  • How to insert nodes at the head
  • How to reverse the list in place using the prev / current / next three-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.

C program that dynamically allocates memory for a linked list and reverses it using a function

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
prevTracks the node that will become the new "next" of the current node
currentThe node currently being reversed
nextSaves 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.

📖 Related Tutorials

  • malloc in C
  • free in C
  • 3. Dynamic 2D Array and Transpose
  • 5. Dynamic Stack — Push and Pop
  • All DMA Assignments

Previous Topic: -->> 3. Dynamic 2D Array & Transpose   ||   Next topic: -->> 5. Dynamic Stack — Push & Pop


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.