Skip to main content

Three Pointers

206. Reverse Linked List

206. Reverse Linked List

Easy2 solutions2 playgrounds

Solutions:

def reverseList(head):
"""Abdul Bari's solution"""
front, mid, back = head, None, None
while front:
front, mid, back = front.next, front, mid
mid.next = back
return mid

Reverse a Doubly Linked List

Reverse a Doubly Linked List

Easy2 solutions2 playgrounds

Solutions:

def reverseDLL(head):
front, mid, back = head, None, None
while front:
front, mid, back = front.next, front, mid
mid.next = back
mid.prev = front
return mid

Reverse both parts

Reverse both parts

Easy1 solution1 playground

Solutions:

During the loop the top panel (head) shows the original list being unwound in place. Once line 41 (new_head = front) fires, a second panel labelled new_head (result) appears with the reversed chain — by the end it contains all nodes in the final [3,2,1,5,4] order for the default preset. The legacy view drew this as two side-by-side reversed segments; the two-panel form makes the same point.

def reverse(head, k):
sep = tail = new_head = None
index = 0
front, mid, back = head, None, None
while front:
if not front.next:
tail = front
if index == k - 1:
new_head = front
if index == k:
sep = front
front, mid, back = front.next, front, mid
mid.next = back
index += 1
 
head.next = tail
sep.next = None
return new_head

24. Swap Nodes in Pairs

24. Swap Nodes in Pairs

Medium3 solutions2 playgrounds

Solutions:

def swapPairs(head):
if not head or not head.next:
return head
sentinel = ListNode(None, next=head)
front, mid, back = head.next, head, sentinel
while front:
mid.next = front.next
front.next = mid
back.next = front
 
back = mid
mid = mid.next
front = mid.next if mid else None
return sentinel.next

Add 1 to a Linked List Number

Add 1 to a Linked List Number

Medium2 solutions2 playgrounds

Solutions:

def addOne(head):
def reverseList(head):
front, mid, back = head, None, None
while front:
front, mid, back = front.next, front, mid
mid.next = back
return mid
 
new_head = reverseList(head)
carry = 1
curr, prev = new_head, None
while curr:
carry, curr.val = divmod(curr.val + carry, 10)
curr, prev = curr.next, curr
if carry:
prev.next = ListNode(carry)
return reverseList(new_head)