NeetCode #303LC-206EasyLinked ListBlind 75NC 150NC 250
← Back to All Problems#303 · #206 · Reverse Linked List(反转链表)
📌 Problem Statement & Constraints
Given the head of a singly linked list, reverse the list and return the new head. Constraints: the number of nodes is in
[0, 5000], -5000 <= Node.val <= 5000. The follow-up asks for both an iterative and a recursive solution.💡 Core Algorithmic Approaches
- Walk the list while maintaining
prev(the already-reversed prefix) andcur(the remaining list). - At each step, save
cur.next, pointcur.nextatprev, then advanceprev = curandcur = saved. - When
curbecomesNone,previs the new head. - Python's simultaneous tuple assignment expresses the three-pointer update in one line, which is both concise and safe.
💻 Benchmark Python3 Implementation
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
cur = head
while cur:
cur.next, prev, cur = prev, cur, cur.next
return prev
# Recursive variant: reverse the tail, then attach the head at the end
class Solution2:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head # base case
new_head = self.reverseList(head.next)
head.next.next = head # the old tail now points back at head
head.next = None # head becomes the new tail
return new_head⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each node is visited once.
💾 Space Complexity
O(1) for the iterative version; O(n) for the recursion stack.
⚠️ Interview Pitfalls & Follow-ups
- Losing the rest of the list:
cur.nextmust be saved before it is overwritten. The tuple assignment does this implicitly. - Returning
head: after the loop,headis the old head, which is now the tail. Returnprev. - Forgetting
head.next = Nonein the recursion: the new tail would still point at the reversed list, creating a cycle. - Using recursion on a long list: Python's default recursion limit is about 1000, so a 5000-node list would overflow.