Reverse a Singly Linked List
Problem statement
Given the head of a singly linked list, reverse the order of its nodes and return the head of the reversed list.
For this practice, each node contains an integer value and a next pointer. An empty list is represented by null and reverses to an empty list. The input and output examples use arrays to display list values in traversal order.
Function
reverseList(head: ListNode) → ListNodeExamples
Example 1
head = [1,2,3,4,5]return = [5,4,3,2,1]The tail node becomes the new head, followed by the previous nodes in reverse order.
Example 2
head = []return = []There are no nodes to reverse, so the result is empty.
Example 3
head = [7,7,-2]return = [-2,7,7]Repeated values remain separate nodes; the value order becomes -2 -> 7 -> 7.
Constraints
- The list contains
0to100nodes. -10^4 <= node.val <= 10^4.- Return the nodes in exact reverse traversal order, preserving every value and occurrence.