Explain reversing a linked list.
Skip to solutionKEEP THE
easyDSA
How do you reverse a linked list?
1.2k views
01
Understand the problem
linked-list
02
Attempt it yourself
Sketch your approach before reading the solution — that's what interviews test.
Nudge consolestandby
Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.
03
Study the solution
Iterate with three pointers — prev, curr, next — and at each step point curr.next back to prev, then advance all three. Returns the new head in O(n) time, O(1) space. It can also be done recursively.
Solution ready — 2 min read
Classified // press E to declassify
04
Read the code
Iterative reversal
Run Playgroundclass ListNode:
def __init__(self, val, nxt=None):
self.val, self.next = val, nxt
def reverse_list(head):
prev, curr = None, head
while curr:
nxt = curr.next # save next
curr.next = prev # flip
prev = curr # advance
curr = nxt
return prev # new head
# --- demo ---
def build(vals):
head = None
for v in reversed(vals): head = ListNode(v, head)
return head
def to_list(head):
out = []
while head: out.append(head.val); head = head.next
return out
print(to_list(reverse_list(build([1, 2, 3])))) # [3, 2, 1]05
Join the discussion
Discussion (0)
Sign in to join the discussion.
No responses yet. Be the first to share what you think.
Transmission complete // awaiting log
KEEP THE
STREAK ALIVE.
Dossier 1 of 127 decoded in the Data Structures & Algorithms track. One more won't hurt.