Reverse Linked List
easyBlind 75NeetCode 150linked-list
Problem
Given the head of a singly linked list, reverse the list in place and return the new head. The reversal should rewire the existing nodes rather than copying values.
Examples
Input: 1 -> 2 -> 3 -> 4 -> 5
Output: 5 -> 4 -> 3 -> 2 -> 1
Pointers are flipped to run in the opposite direction.
Input: empty list
Output: empty list
Reversing nothing yields nothing.
Constraints
- • 0 <= number of nodes <= 5000
- • -5000 <= node value <= 5000
Hints(tap to reveal)
- 1. Walk the list flipping each next pointer.
- 2. Keep three references: previous, current, and the saved next.
Optimal approach(spoiler)
- Initialize a previous pointer to null and current to the head.
- At each node save its next, point current's next to previous.
- Advance previous to current and current to the saved next.
- When current is null, previous is the new head.
- O(n) time, O(1) space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor