Skip to main content

Three Pointers

206. Reverse Linked List​

2 Approaches
FIG. REVERSE LINKED LIST● INTERACTIVE
visualization loads as you reach it
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​

Easy·
2 Approaches
FIG. REVERSE A DOUBLY LINKED LIST● INTERACTIVE
visualization loads as you reach it
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​

Easy·
FIG. REVERSE BOTH PARTS● INTERACTIVE
visualization loads as you reach it
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​

Medium·
3 Approaches
FIG. SWAP NODES IN PAIRS● INTERACTIVE
visualization loads as you reach it
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