Overview
Given the head of a singly linked list, reverse the list and return the new head.
Constraints
- The list has 0 to 5,000 nodes.
- Node values are integers.
- Solve iteratively using O(1) extra space.
Examples
// 1 -> 2 -> 3 -> 4 -> 5 reverseList(head); // => 5 -> 4 -> 3 -> 2 -> 1
// 1 -> 2 reverseList(head); // => 2 -> 1 // null reverseList(null); // => null
Solution
Reveal solution
function reverseList(head) {
let prev = null;
let curr = head;
while (curr) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}Resources
linked-list-reversal.js
Linked List Reversal
easycodingAlgorithmsLinked Lists
Overview
Given the head of a singly linked list, reverse the list and return the new head.
Constraints
- The list has 0 to 5,000 nodes.
- Node values are integers.
- Solve iteratively using O(1) extra space.
Examples
// 1 -> 2 -> 3 -> 4 -> 5 reverseList(head); // => 5 -> 4 -> 3 -> 2 -> 1
// 1 -> 2 reverseList(head); // => 2 -> 1 // null reverseList(null); // => null
Solution
Reveal solution
function reverseList(head) {
let prev = null;
let curr = head;
while (curr) {
const next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}Resources
NameTopicDifficulty
103 of 103 problems