Reversing a linked list in C, visualized step by step
Walk from the head to the tail and point each node's next back at the node before it. Save the next node first: once a pointer is changed, the rest of the list would be lost.
reverse_linked_list.c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node *next;
} Node;
Node *push(Node *head, int val) {
Node *n = malloc(sizeof(Node));
n->val = val;
n->next = head;
return n;
}
int main(void) {
Node *head = NULL;
for (int v = 4; v >= 1; v--) head = push(head, v);
Node *prev = NULL, *cur = head;
while (cur) {
Node *next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
head = prev;
for (Node *p = head; p; p = p->next) printf("%d ", p->val);
printf("\n");
while (head) {
Node *next = head->next;
free(head);
head = next;
}
return 0;
}
How Reverse a linked list works
- prev starts empty; cur points at the head.
- Save the node after cur (next).
- Point cur's next at prev: this node now faces back.
- Move prev and cur one step forward; when cur is empty, prev is the new head.
What to watch
The arrowsEach step turns one node's arrow from right to left.
nextIt holds on to the part not reversed yet; without it the list breaks.
FAQ
What is the time complexity of reversing a linked list?
O(n): each node is visited once. Only a few pointers are used, so the extra space is O(1).
What is the most common mistake?
Changing cur's next before saving the next node: by then it points backwards, and the rest of the list is gone. Save next first.
Can it be done recursively?
Yes, but recursion uses O(n) stack and can overflow on a long list. Interviews usually expect both.