Reverse Linked List
Given the head of a singly linked list, flip the direction of the entire list so what used to be the last node becomes the first, and return this new head.
Achieve this by rewiring each node's next pointer — either an iterative loop or a recursive approach works.
Input Format
Implement reverseList(head). Inputs below show JavaScript function arguments; there is no stdin parsing.
Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.
Output Format
Return the result described in the statement.
Returned list heads are displayed as value arrays; a null head is [].
Sample Input and Output
Example 1 · Run Sample
Input
head = [1,2,3,4,5] Output
[5,4,3,2,1] Example 2
Input
head = [] Output
[] Constraints
- 0 to 5000 nodes
- -5000 <= Node.val <= 5000
Test Cases (2)
Case 1
Args: [[1,2,3,4,5]]
Expected: [5,4,3,2,1]
Case 2
Args: [[]]
Expected: []
Topics
Iterative
function reverseList(head) {
let prev = null, curr = head;
while (curr) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}Time: O(n) | Space: O(1)
Saved in this browser only. Private to you.