Space
Open
From Fieldwork
Scales
Archive
The strategy is broken down into three distinct steps:
class Solution:
def reorderList(self, head: ListNode) -> None:
if not head or not head.next:
return
# Step 1: Find the Middle
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# 'slow' is now at the end of the first half.
# We split the list here.
second = slow.next
slow.next = None # Cut the first half
# Step 2: Reverse Second Half
prev = None
curr = second
while curr:
next_temp = curr.next
curr.next = prev
prev = curr
curr = next_temp
# 'prev' is now the head of the reversed second half
# Step 3: Merge the Two Halves
first, second = head, prev
while second:
# Save next pointers
tmp1, tmp2 = first.next, second.next
# Link first to second
first.next = second
# Link second to old first.next
second.next = tmp1
# Move pointers forward
first, second = tmp1, tmp2Practice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode