⌘K
Flycodx

Reverse a Linked List

Reverse a Linked List

EasyLinked Lists41% accepted

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

5 1 2 3 4 5

Output

5 4 3 2 1
  • •1 ≤ n ≤ 10^4, -10^9 ≤ node values ≤ 10^9
solution.py
Loading editor...
Test 1
Test 2
Test 3

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
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3