Reverse Linked List

easyLinked Listiterative pointer reversal (prev/curr)B75Solve on LeetCode#206

Part of Practice: Core Surgery

Given the head of a singly linked list — a chain of nodes where each node stores a value and a next pointer to the following node — reverse the chain and return the new head.

So the list 1 -> 2 -> 3 becomes 3 -> 2 -> 1. The list can be empty, and it can hold up to 5000 nodes. Do it in O(n) time without allocating a new list.

Examples

Input:
head = [1, 2, 3, 4, 5]
Output:
[5, 4, 3, 2, 1]
Input:
head = [1, 2]
Output:
[2, 1]
Input:
head = []
Output:
[]

An empty list reverses to an empty list.

Hints

One at a time — struggle first, peek second.

Your thinking space — verify on LeetCode, then mark it.