CodingNodes / Linked List / Reverse Linked List System design Space play · ←→ step · R restart

Problem

You are given the head of a singly linked list. Turn the list around so that the last node becomes the first and every arrow points the other way.

Return the new head. An empty list stays empty.

Constraints

  • 0 ≤ number of nodes ≤ 5000
  • -5000 ≤ Node.val ≤ 5000

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: Every node is visited once and its arrow is turned once.

Space: Only the prev, cur and next pointers are kept. The nodes are reused, not copied.

Walk down the list with two pointers. Before turning cur's arrow back to prev, save cur's old next so you do not lose the rest of the list. Then step both pointers forward.