class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def reorderList(head: ListNode) -> None:
if not head or not head.next:
return
# Find middle
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# Split and reverse second half
second = slow.next
slow.next = None
prev = None
while second:
tmp = second.next
second.next = prev
prev = second
second = tmp
# Merge two halves
first, second = head, prev
while second:
tmp1, tmp2 = first.next, second.next
first.next = second
second.next = tmp1
first, second = tmp1, tmp2
# Helper to print list
def printList(head: ListNode) -> None:
curr = head
res = []
while curr:
res.append(str(curr.val))
curr = curr.next
print(" -> ".join(res) + " -> null")
# Driver code
head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
printList(head)
reorderList(head)
printList(head)while fast and fast.next:
advance slow and fast pointers to find middle node
second = slow.next
slow.next = None
split list into two halves by breaking link at middle
while second:
tmp = second.next
second.next = prev
prev = second
second = tmp
reverse second half of the list
while second:
tmp1, tmp2 = first.next, second.next
first.next = second
second.next = tmp1
first, second = tmp1, tmp2
merge nodes from first and reversed second half alternately
1 -> 2 -> 3 -> 4 -> 5 -> null
1 -> 5 -> 2 -> 4 -> 3 -> null