Faaez Razeen

Reorder List

  • 2 min read
  • LC-Medium
  • Linked List

3 years ago

Solution

first, second = head, prev while second: t1, t2 = first.next, second.next first.next = second second.next = t1 first, second = t1, t2
TimeSpaceExplanation
O(n)O(1)
def reorderList(self, head: Optional[ListNode]) -> None: # find middle of list slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next # reverse 2nd half of list prev, curr = None, slow.next while curr: next = curr.next curr.next = prev prev = curr curr = next slow.next = None # Remove link from last node of first list so that cycle doesn't occur # Alternate between lists and change links first, second = head, prev while second: # This is valid because the second list would be the shorter of the two lists t1, t2 = first.next, second.next first.next = second second.next = t1 first, second = t1, t2