Reverse Linked List
Given the head of a singly linked list, reverse the list so that the last node becomes the new head and every next pointer points to the node that used to precede it. Return the new head.
Open official problem prompt ↗Produce the same nodes linked in the opposite order, returning the former tail as the new head, without allocating a second list.
Like reversing a chain of train cars by re-coupling each car to the one behind it — you must hold the next car before you unhook it, or it rolls away.
- Input
- head = [1, 2, 3, 4, 5]
- Output
- [5, 4, 3, 2, 1]
- Why
- Each node's next pointer is flipped, so traversal now starts at 5 and ends at 1.
The number of nodes is in the range [0, 5000]-5000 <= Node.val <= 5000