Reverse a Linked List
Completed
Build a list from n integers, reverse it in place by re-pointing the links, and print it.
Input
Line 1: n. Line 2: n integers.
Output
One line.
Example
Input
5 1 2 3 4 5
Output
5 4 3 2 1
Editor
C
Hints
Walk the list keeping prev, cur and next; point cur->next back to prev.
Solution explanation
This three-pointer reversal is one of the most famous pointer exercises.
Show solution
#include <stdio.h>
#include <stdlib.h>
struct Node {
int value;
struct Node *next;
};
int main() {
int n, x;
struct Node *head = NULL, *tail = NULL;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &x);
struct Node *node = malloc(sizeof(struct Node));
node->value = x;
node->next = NULL;
if (head == NULL) head = node;
else tail->next = node;
tail = node;
}
struct Node *prev = NULL, *cur = head;
while (cur != NULL) {
struct Node *next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
head = prev;
for (struct Node *p = head; p != NULL; p = p->next) printf("%d ", p->value);
printf("\n");
return 0;
}