Reverse Linked List
Easy · linked list
You are given the head of a singly linked list. Reverse the list so that every node points to the node that used to come before it, and return the head of the reversed list.
An empty list (head is None) reverses to an empty list. The nodes you receive are ListNode objects with a val and a next; you may re-point them or change their values.
Examples
Example 1
Input: head = [1, 2, 3, 4]
Output: [4, 3, 2, 1]
The old tail 4 becomes the new head, and each arrow now points backwards.
Example 2
Input: head = [7, 9]
Output: [9, 7]
Example 3
Input: head = []
Output: []
Constraints
- 0 <= number of nodes <= 5000
- -5000 <= Node.val <= 5000