
Given the head of a singly linked list, reverse the list and return the new head. Each node contains an integer value and a next pointer. The function should modify the links between nodes rather than creating a new list.
Example 1:
Input: head = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
Explanation: The next pointers are reversed so the tail becomes the new head.
Example 2:
Input: head = [1, 2]
Output: [2, 1]
Explanation: The second node points to the first node after reversal.
Example 3:
Input: head = []
Output: []
Explanation: An empty list remains empty.
0 <= number of nodes <= 5000-5000 <= node.val <= 5000O(n) time and O(1) extra spacehead = [1, 2, 3, 4, 5]Output[5, 4, 3, 2, 1]WhyEach next pointer is reversed, so the original tail becomes the new head.head = [1, 2]Output[2, 1]WhyThe second node points to the first node after reversal.head = []Output[]WhyThere are no nodes to reverse, so the result is still empty.0 <= number of nodes <= 5000-5000 <= node.val <= 5000The list is singly linkedAim for O(n) time and O(1) extra spacedef reverse_linked_list(head):