All coding questions

Reverse Linked List

easy
Blind 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)
  1. Initialize a previous pointer to null and current to the head.
  2. At each node save its next, point current's next to previous.
  3. Advance previous to current and current to the saved next.
  4. When current is null, previous is the new head.
  5. 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