class Solution: def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]: # Base case if not head or not head.next: return head # Step 1: Split the list into two halves slow, fast = head, head.next while fast and fast.next: slow = slow.next fast = fast.next.next mid = slow.next slow.next = None # Cut the list # Step 2: Sort each half recursively left = self.sortList(head) right = self.sortList(mid) # Step 3: Merge the sorted halves return self.merge(left, right) def merge(self, list1: ListNode, list2: ListNode) -> ListNode: dummy = ListNode(0) tail = dummy while list1 and list2: if list1.val <= list2.val: tail.next = list1 list1 = list1.next else: tail.next = list2 list2 = list2.next tail = tail.next # Connect remaining nodes tail.next = list1 if list1 else list2 return dummy.next