At Stripe, a service stores events in a singly linked list. Write a function that reverses the list in-place and returns the new head.
Implement a function that takes the head of a singly linked list, where each node has fields val and next, and returns the head of the reversed list.
head, the first node of a singly linked list, or null for an empty listExample 1
head = [1, 2, 3, 4, 5][5, 4, 3, 2, 1]next pointer is redirected to the previous node.Example 2
head = [7, 9][9, 7]next points to the first node.0 <= number of nodes <= 5000-10^4 <= node.val <= 10^4O(n) time and O(1) extra spaceA correct solution should handle empty lists and single-node lists without errors.
head = [1, 2, 3, 4, 5]Output[5, 4, 3, 2, 1]WhyThe list is reversed by redirecting each `next` pointer to the previous node.head = [7, 9]Output[9, 7]WhyAfter reversal, `9` becomes the head and points to `7`.head = []Output[]WhyAn empty list remains empty after reversal.0 <= number of nodes <= 5000-10^4 <= node.val <= 10^4Each node has fields `val` and `next`The list is singly linkedReverse the list in-placedef reverse_linked_list(head):