Skills101
← All coding problems

Reverse Linked List

easyLinked List+10 XPTime limit 2s

Reverse a singly linked list and print it.

List format. A linked list is given as two lines: its length n, then its n values from head to tail (the second line is empty when n = 0). When you print a list, print its values on one line separated by spaces, or the word empty if it has no nodes.

Input: one list.

Output: the reversed list.

Constraints: 0 ≤ n ≤ 10⁵, −1000 ≤ value ≤ 1000.

Practise the real skill: the starter code builds actual Node objects. Reverse the links in place with three pointers — prev, curr, next — in O(n) time and O(1) memory. Then try the recursive version (careful: very long lists can overflow the call stack).

Sample input 1

5
1 2 3 4 5

Sample output 1

5 4 3 2 1

Sample input 2

2
1 2

Sample output 2

2 1

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.