Skip to problem
←

Reverse Linked List

Easy 0 attempts

Given the head of a singly linked list, reverse the order of its original nodes by rewiring their next pointers, then return the new head.

Do not change node values or create replacement nodes. Include every original node exactly once. The old head becomes the tail and must point to null; the old tail becomes the new head.

An empty list returns null, and a single-node list returns that same node. For 1 → 2 → 3 → null, return the original node 3, linked as 3 → 2 → 1 → null.

Examples display lists as arrays, but your function receives nodes with val and next properties. An iterative solution can use constant extra space.

Function contract

Implement reverseList(head). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Return the original tail as the new head after reversing every next link, or null for an empty list. The runner displays the final values as an array.

Example 1

Input
head = [1,2,3,4,5]
Output
[5,4,3,2,1]

Example 2

Input
head = []
Output
[]
Constraints
  • 0 to 5000 nodes
  • -5000 <= Node.val <= 5000
Topics

Reverse One Link at a Time

Keep prev as the head of the already-reversed prefix and curr as the first unprocessed node. Initially the prefix is empty, so prev is null.

Save curr.next before changing it, point curr.next back to prev, then advance both pointers using the saved link. Saving first prevents losing access to the unprocessed suffix.

When curr reaches null, every link has been reversed and prev is the new head. The first rewiring sets the old head's next pointer to null, making it the final tail. The loop preserves every node and its value.

javascript
function reverseList(head) {
  let prev = null,
    curr = head;
  while (curr) {
    const next = curr.next;
    curr.next = prev;
    prev = curr;
    curr = next;
  }
  return prev;
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript