Reverse Linked List

Easy

Topics
Linked ListRecursion

Given the head of a singly linked list, reverse the list and return the new head. Lists are shown as arrays of node values.

Example 1

before1head2345null
after5head4321null
Each node’s next is flipped to point at its predecessor. Three pointers are needed, not two: the next node must be saved before the link is overwritten, or the rest of the list is lost. The old head becomes the tail and now points at null.
Linked list values from head to tail.
Input:  head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2

empty list
Input:  head = []
Output: []

Constraints

  • 0 <= number of nodes <= 5000
  • -5000 <= Node.val <= 5000
Editorial — intuition, approach, complexity and pitfalls

Intuition

Reversing a singly linked list means flipping each next pointer to point backwards. Keep a prev pointer that trails behind and becomes the new head.

Approach

  1. Walk the list with curr, remembering the next node before you overwrite the pointer.
  2. Point curr.next back to prev.
  3. Advance prev and curr; when curr is null, prev is the new head.

Dry Run

1 -> 2 -> 3 -> 4 -> 5
Three pointers: prev trails behind, curr is where we are, nxt is the rescued
remainder of the original list.
  start    prev = null              curr = 1->2->3->4->5
  step 1   prev = 1                 curr = 2->3->4->5
  step 2   prev = 2->1              curr = 3->4->5
  step 3   prev = 3->2->1           curr = 4->5
  step 4   prev = 4->3->2->1        curr = 5
  step 5   prev = 5->4->3->2->1     curr = null
answer 5->4->3->2->1
Watch the two chains in the middle column. prev grows reversed from the front
while curr shrinks from the front, and together they always hold all five nodes --
nothing is ever copied, only re-pointed, which is the O(1) space.
`nxt = curr.next` has to come first. The very next statement overwrites curr.next,
so without that save the rest of the list is unreachable the instant the first
pointer is flipped: step 1 would leave prev = 1 and no way to find the 2.
The loop ends when curr is null, and at that moment prev is sitting on the last
node of the original list, which is the new head. Returning curr instead returns
null -- a one-character slip with a silent empty result.

Complexity

  • Time — O(n): each node is visited once.
  • Space — O(1): only three pointers (iterative).

Common Pitfalls

  • Save curr.next before reassigning it, or you lose the rest of the list.

Full Solution — all languages

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def reverseList(self, head):
        prev=None
        curr=head
        while curr:
            nxt=curr.next
            curr.next=prev
            prev=curr
            curr=nxt
        return prev
SensAI
Beta
Tap the mic to stop voice mode