Reverse a Linked List
Problem statement
Given the head of a singly linked list, reverse its links and return the new head.
Reuse the existing nodes. Each node must point to the node that preceded it in the original list; the original head becomes the tail and points to null.
The input is acyclic. An empty list remains empty. Lists are displayed as arrays of their node values.
Function
reverseList(head: ListNode) → ListNodeExamples
Example 1
head = [2,5,8]return = [8,5,2]The original last node becomes the head. The node order changes from 2 → 5 → 8 to 8 → 5 → 2.
Example 2
head = [4,4,-1]return = [-1,4,4]Reversal preserves all three nodes, including both nodes with value 4.
Constraints
- The list has
0to1000nodes. - Each node value is an integer in
[-10^6, 10^6]. - Node values may repeat.
- The input contains no cycle.