Reverse Linked List - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

We reverse the linked list in-place by maintaining two pointers: reversedListHead and current.
This iterative approach flips each node’s pointer one by one, reversing the list efficiently with constant extra space.

  1. Initialize pointers:
    Set reversedListHead = null and current = head.
    At the start, nothing is reversed yet β€” reversedListHead marks the head of the reversed portion (initially empty), and current points to the first not yet processed node of the original list.
  2. Iterate and reverse links:
    While current is not null:
    • Store next = current.next β€” to preserve access to the rest of the list before breaking the link.
    • Reverse the arrow by setting current.next = reversedListHead.
    • Advance pointers: reversedListHead = current and current = next.
    Each iteration extends the reversed portion by one node.
  3. Termination:
    When current becomes null, the entire list has been reversed.

    βœ… Why reversedListHead is now the new head:
    reversedListHead always points to the head of the reversed portion. Once the loop finishes, that portion includes every node β€” so reversedListHead is the head of the fully reversed list.

Time Complexity

O(n), where n is the number of nodes β€” each node is visited once.

Space Complexity

O(1) β€” only a few pointers are used regardless of list size.

Visucodize editorial solution titled JS Solution for LeetCode's Reverse Linked List coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/reverse-linked-list.