Reversing a linked list
suggest changeYou can also perform this task recursively, but this example uses an iterative approach. Reversal is useful when nodes were inserted at the beginning of a singly linked list, because that insertion order is the reverse of the values. Here is an example:
#include <stdio.h>
#include <stdlib.h>
#define NUM_ITEMS 10
struct Node {
int data;
struct Node *next;
};
void insert_node(struct Node **headNode, int nodeValue, int position);
void print_list(struct Node *headNode);
void reverse_list(struct Node **headNode);
int main(void) {
int i;
struct Node *head = NULL;
for(i = 1; i <= NUM_ITEMS; i++) {
insert_node(&head, i, i);
}
print_list(head);
printf("I will now reverse the linked list\n");
reverse_list(&head);
print_list(head);
return 0;
}
void print_list(struct Node *headNode) {
struct Node *iterator;
for(iterator = headNode; iterator != NULL; iterator = iterator->next) {
printf("Value: %d\n", iterator->data);
}
}
void insert_node(struct Node **headNode, int nodeValue, int position) {
int i;
struct Node *currentNode = malloc(sizeof *currentNode);
struct Node *nodeBeforePosition = *headNode;
if (currentNode == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
currentNode->data = nodeValue;
if(position == 1) {
currentNode->next = *headNode;
*headNode = currentNode;
return;
}
for (i = 0; i < position - 2; i++) {
nodeBeforePosition = nodeBeforePosition->next;
}
currentNode->next = nodeBeforePosition->next;
nodeBeforePosition->next = currentNode;
}
void reverse_list(struct Node **headNode) {
struct Node *iterator = *headNode;
struct Node *previousNode = NULL;
struct Node *nextNode = NULL;
while (iterator != NULL) {
nextNode = iterator->next;
iterator->next = previousNode;
previousNode = iterator;
iterator = nextNode;
}
/* Iterator will be NULL by the end, so the last node will be stored in
previousNode. We will set the last node to be the headNode */
*headNode = previousNode;
}
Explanation for the Reverse List Method
previousNode starts as NULL. On the first iteration there is no node before the original head, so the original head becomes the tail and its next member should be NULL.
The algorithm reverses the links themselves. Each node’s next member is set to the node that used to precede it:
Head -> 1 -> 2 -> 3 -> 4 -> 5
Where each number represents a node. This list would become:
1 <- 2 <- 3 <- 4 <- 5 <- Head
Finally, the head should point at node 5, and each node should point at the node that previously preceded it.
Node 1 should point to NULL because nothing preceded it. Node 2 should point to node 1, node 3 should point to node 2, and so on.
If the link to the next node is overwritten before that node is saved, the rest of the list is no longer reachable.
The solution to this problem is to simply store the next element in a variable (nextNode) before changing the link.