Reverse a Linked List
Problem statement
Given the head of a singly linked list, reverse the order of its nodes and return the new head.
The input list is finite and has no cycle. An empty list is represented by []; return an empty list for that input.
For example, the list [2, 5, 8] becomes [8, 5, 2]. Duplicate and negative values remain unchanged.
Function
reverseList(head: ListNode) → ListNodeExamples
Example 1
head = [2,5,8]return = [8,5,2]The last node becomes the head. Following the reversed links visits 8, then 5, then 2.
Example 2
head = []return = []There are no nodes to reverse, so the result is an empty list.
Constraints
- The list contains between
0and5000nodes. - Each node value is between
-5000and5000, inclusive. - The input is a finite, acyclic singly linked list.