# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defsortList(self, head: Optional[ListNode]) -> Optional[ListNode]: defmergeTwoList(list1, list2): ifnot list1: return list2 ifnot list2: return list1
dummy = ListNode() p = dummy while list1 and list2: if list1.val < list2.val: p.next = list1 list1 = list1.next else: p.next = list2 list2 = list2.next p = p.next p.next = list1 if list1 else list2 return dummy.next defhelper(head, tail): ifnot head: return head if head.next == tail: head.next = None return head slow = head fast = head while fast != tail: slow = slow.next fast = fast.next if fast != tail: fast = fast.next mid = slow return mergeTwoList(helper(head, mid), helper(mid, tail)) return helper(head, None)