Command Palette
Search for a command to run...
Problem 8.1 · Linked ListsEasy
What it teaches: The three-pointer reversal you'll reuse in palindrome checks, reordering and group reversal.
Practise it on judges as “Reverse Linked List”.
The problem
Given the head of a singly linked list, reverse it and return the new head.
Example 1
Input: head = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
Example 2
Input: head = []
Output: []
Constraints
- 0 ≤ number of nodes ≤ 5000
Pattern clues in the wording
- → Reverse the direction of links
- → O(1) extra space is possible
These clues point to In-Place Linked List Reversal: Walk the list with prev, curr and next, turning each arrow around as you go.
Stuck? Take one hint at a time
Solution.java · starterclass Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null, curr = head;
return prev;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Test cases
| # | Input | Expected |
|---|
| 1 | head = [1,2,3,4,5] | [5,4,3,2,1] |
| 2 | head = [1,2] | [2,1] |
| 3 | head = [] | [] |
+ 1 hidden test the code runner will check