Step-by-Step Guide: Reversing a Linked List in C
Introduction
This guide explains how to reverse a singly linked list in C using both iterative and recursive methods with
visual formatting and detailed steps.
Step 1: Define the Node Structure
We define a struct for a singly linked list node. Each node has an integer data and a pointer to the next node.
struct Node {
int data;
struct Node* next;
};
Step 2: Create a New Node
We define a function to allocate memory for a new node, assign data, and initialize the next pointer to NULL.
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
Step 3: Print the Linked List
This function traverses and prints each node's data.
void printList(struct Node* head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
Step 4: Iteratively Reverse the List
In this method, we use three pointers: prev, current, and next to reverse the list by changing the direction of
links.
struct Node* reverseIterative(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;
Step-by-Step Guide: Reversing a Linked List in C
return prev;
}
Step 5: Recursively Reverse the List
This method works by reversing the rest of the list and fixing the current node's next pointer during the return
phase of recursion.
struct Node* reverseRecursive(struct Node* head) {
if (head == NULL || head->next == NULL)
return head;
struct Node* rest = reverseRecursive(head->next);
head->next->next = head;
head->next = NULL;
return rest;
}
Step 6: Main Function
We create a simple list and call both the iterative and recursive functions to demonstrate the reversal.
int main() {
struct Node* head = createNode(10);
head->next = createNode(20);
head->next->next = createNode(30);
head->next->next->next = createNode(40);
printf("Original List:\n");
printList(head);
head = reverseIterative(head);
printf("\nReversed List (Iterative):\n");
printList(head);
head = reverseRecursive(head);
printf("\nReversed List (Recursive):\n");
printList(head);
return 0;
}
Expected Output
Original List:
10 -> 20 -> 30 -> 40 -> NULL
Step-by-Step Guide: Reversing a Linked List in C
Reversed List (Iterative):
40 -> 30 -> 20 -> 10 -> NULL
Reversed List (Recursive):
10 -> 20 -> 30 -> 40 -> NULL