↓Skip to main content
  1. LeetCode/

LeetCode 206: Reverse Linked List

·1 min· ·
LeetCode Easy Linked-List Recursion
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-21

  • Submissions: Runtime Error → Accepted → Wrong Answer → Accepted ×2

Approach
#

Point each cur.next back to the previous node (Linked List Template 2). Save cur.next before overwriting it, or the rest of the list is lost. At the end prev is the new head; for an empty list prev is None, also correct.

My Attempts
#

Attempt 1 used an undefined variable (NameError); a later rewrite missed the empty list and read head.next on [].

Solution
#

class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        prev, cur = None, head
        while cur:
            nxt = cur.next
            cur.next = prev
            prev, cur = cur, nxt
        return prev

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Save cur.next before changing it.
  • An empty list needs no special case: the loop is skipped and None is returned.

Interview Explanation
#

With prev and cur, each step saves the next node, points cur.next at prev, and moves both forward. prev ends as the new head. Time O(n), space O(1).

Related

LeetCode 203: Remove Linked List Elements
·2 mins
LeetCode Easy Linked-List Recursion
LeetCode 203 note: the head may be deleted too, so a dummy head turns every deletion into deleting cur.next; do not advance after deleting
LeetCode 141: Linked List Cycle
·2 mins
LeetCode Easy Hash-Table Linked-List Two-Pointers Floyds-Cycle-Finding-Algorithm
LeetCode 141 note: Floyd’s cycle detection, fast two steps and slow one; with a cycle they must meet, each advancing from its own position
LeetCode 160: Intersection of Two Linked Lists
·2 mins
LeetCode Easy Hash-Table Linked-List Two-Pointers
LeetCode 160 note: each pointer walks its own list then the other’s; both cover lenA + lenB steps and reach the intersection, or None, together
LeetCode 83: Remove Duplicates from Sorted List
·2 mins
LeetCode Easy Linked-List
LeetCode 83 note: sorted, so duplicates are adjacent; skip cur.next while it equals cur, and advance only otherwise
LeetCode 2: Add Two Numbers
·2 mins
LeetCode Medium Linked-List Math Recursion
LeetCode 2 note: digits are stored in reverse, so add from the head digit by digit with a carry, looping until both lists end and no carry remains
LeetCode 171: Excel Sheet Column Number
·1 min
LeetCode Easy Math String
LeetCode 171 note: scan left to right with res = res × 26 + letter value (A = 1)