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^4