Reverse a linked list
Easylinked listtwo pointersrecursion
Given head, the first node of a linked list, reverse the list and return the new first node.
Examples write a list as an array: [1,2,3] means 1 → 2 → 3.
Example 1
Input: head = [1,2,3,4,5] Output: [5,4,3,2,1]
Example 2
Input: head = [1,2] Output: [2,1]
Example 3
Input: head = [] Output: []
An empty list stays empty.
Constraints
- 0 ≤ number of nodes ≤ 5000
- -5000 ≤ Node.val ≤ 5000
Submit checks your solution against 8 tests, including hidden ones.
// Provided by the judge: keep these definitions
class ListNode {
constructor(val = 0, next = null) {
this.val = val
this.next = next
}
}
/**
* @param {ListNode|null} head
* @return {ListNode|null}
*/
function reverseList(head) {
}