SDE & MLE Prep

206. Reverse Linked List

Problem

Reverse a singly linked list and return the new head.

Example: 1→2→3→4→5 → 5→4→3→2→1

Constraints: follow-up: both iteratively and recursively.

Iteratively flip each next pointer while walking forward.

Complexity: O(n) time, O(1) space (recursive version uses O(n) stack).

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