Given the head of a singly linked list, reverse the list and return the new head.
Walk the list with three pointers — prev, curr, next — and at each step flip curr.next to point at prev before advancing. The previous head becomes the tail; the previous tail becomes the new head.
[0, 5000].-5000 ≤ Node.val ≤ 5000Track three pointers: prev, curr, next. Save next before overwriting curr.next.
A singly linked list is a chain of arrows. Node 1 knows where 2 is, 2 knows where 3 is, and nobody knows who points at them. Reversing the list doesn't move any values: it turns every arrow around, so 2 points at 1 instead of 3, and the old last node becomes the head.
Time O(n)Space O(1)
The full walkthrough and code in five languages, free to read