


At Stripe, a service stores events in a singly linked list. Write a function that reverses the linked list and returns the new head.
Implement reverse_linked_list(head) where head is the first node of a singly linked list, or null for an empty list. Each node has two fields: val and next. Return the new head of the reversed list.
You must reverse the list by changing node pointers, not by creating a second list of copied 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^4O(n) time and O(1) extra spacehead = [1, 2, 3, 4, 5]Output[5, 4, 3, 2, 1]WhyThe links are reversed in place, so the last node becomes the new head.head = [7]Output[7]WhyA list with one node does not change after reversal.head = []Output[]WhyThere are no nodes to reverse, so the result is still empty.The number of nodes is in the range [0, 5000]-10^4 <= Node.val <= 10^4Each node has fields val and nextThe list is singly linkeddef reverse_linked_list(head):