
In a low-level systems context such as firmware components used in Google hardware, linked-list pointer updates must be done carefully. Implement a function that reverses a singly linked list and returns the new head.
You are given the head of a singly linked list, where each node has two fields: val and next. Return the head of the same list after reversing all next pointers.
Function input: head, a ListNode object or None
Function output: a ListNode object or None
You must reverse the list in place by reusing the existing nodes.
Example 1
Input: head = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
Explanation: Each node's next pointer is reversed, so the tail becomes the new head.
Example 2
Input: head = [7]
Output: [7]
Explanation: A single-node list is already reversed.
Example 3
Input: head = []
Output: []
Explanation: An empty list remains empty.
[0, 5000]-10^4 <= Node.val <= 10^4head = [1, 2, 3, 4, 5]Output[5, 4, 3, 2, 1]WhyThe links are reversed in place, so the original tail becomes the new head.head = [7]Output[7]WhyA single node has no links to reverse.head = []Output[]WhyAn empty list remains empty after reversal.The number of nodes is in the range [0, 5000]-10^4 <= Node.val <= 10^4The list is singly linkedReverse the list in place for the primary solutiondef reverse_linked_list(head):