Reverse a Linked List
Reverse a Linked List
Given the values of a singly linked list, reverse the list so that the last node becomes the head and the first node becomes the tail. Print the reversed values. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: n=5, values=[1 2 3 4 5] → "5 4 3 2 1"
Input format — only if your code reads from stdin
Input format (stdin): - First line: integer n (number of nodes) - Second line: n space-separated integers (node values in order from head to tail) Output: the node values of the reversed list, space-separated on a single line.
Approach
Iterative approach with three pointers: prev (initially null), curr (initially head), and next. In each step: save curr.next, set curr.next = prev, advance prev = curr, advance curr = next. When curr is null, prev is the new head.
Input
Output
- •
1 ≤ n ≤ 10^4, -10^9 ≤ node values ≤ 10^9
More Linked Lists problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards