all entries
A-035Day 352026.06.10easyleetcode #206neetcode150

Reverse Linked List

#linked-list#recursion
leetcode #206 · reverse-linked-list
01

Problem

· problem
P.035

Reverse Linked List

leetcode #206

Given the head of a singly linked list, reverse the list, and return the reversed list.

constraints
  • · 0 ≤ number of nodes ≤ 5000
  • · -5000 ≤ Node.val ≤ 5000
// paraphrased summary — see source for full text
examples
example 1input → output
[1,2,3,4,5]
[5,4,3,2,1]
example 2input → output
[1,2]
[2,1]
example 3input → output
[]
[]
02

Pre-solve

· pre-solve
● 1list shown● 2select● 3reveal
  • Can we reverse the list in-place, or can we create a new list?
  • What should we return if the input is an empty list?
  • Can we assume the input is always a valid singly linked list?
  • Should we swap node values or just rearrange the pointers?
  • Do we need to handle lists with cycles?
  • Can we use the same approach for doubly linked lists?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03

Logic Structure

· logic
● 1slots shown● 2pick per slot● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Initialize Pointers
prev, curr = None, head
prev, curr = head, None
prev = None; curr = head.next
step 2· Loop While Nodes Exist
while curr:
while curr.next:
while prev:
step 3· Save Next Nodenested
temp = curr.next
temp = prev
# (omitted)
step 4· Reverse the Linknested
curr.next = prev
prev.next = curr
curr.prev = prev
step 5· Advance prevnested
prev = curr
prev = temp
prev = None
step 6· Advance currnested
curr = temp
curr = prev
curr = curr.next
step 7· Return New Head
return prev
return curr
return head
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04

Solve · Trace

· solve
solution.py
1
# Definition for singly-linked list.
2
# class ListNode:
3
#     def __init__(self, x):
4
#         self.val = x
5
#         self.next = None
6
7
8
class Solution:
9
    def reverseList(self, head: ListNode) -> ListNode:
10
        prev, curr = None, head
11
12
        while curr:
13
            temp = curr.next
14
            curr.next = prev
15
            prev = curr
16
            curr = temp
17
        return prev
mental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
[1,2,3,4,5]
[5,4,3,2,1]
case 2
[1,2]
[2,1]
case 3
[]
[]
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.