Understanding Reverse Linked List
Reverse a singly linked list and return its new head. The input editor accepts the list as an array; your JavaScript function receives a ListNode or null.
How it works
Save the next node before overwriting the current link, or the unreversed part of the list becomes unreachable.
Track prev, current, and next. Save next, redirect current.next to prev, then advance prev and current. Return prev when current is null.
Try an example
Input: values = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
The original tail becomes the new head.
Constraints
- Each node has val and next properties.
- Preserve nodes and reverse the next links.
- Visualization limit: 32 nodes.
Use the simulator
Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.
Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.