Copy # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution :
def middleNode ( self , head : ListNode) -> ListNode:
fast , slow = head . next , head
while fast and fast . next :
fast = fast . next . next
slow = slow . next
mid = slow . next
slow . next = None
return mid
def mergeTwoLists ( self , l1 : ListNode , l2 : ListNode) -> ListNode:
prevHead = ListNode ( - 1 )
prev = prevHead
while l1 and l2 :
if l1 . val <= l2 . val :
prev . next = l1
l1 = l1 . next
else :
prev . next = l2
l2 = l2 . next
prev = prev . next
prev . next = l1 if l1 else l2
return prevHead . next
def sortList ( self , head : Optional [ ListNode ] ) -> Optional [ ListNode ] :
if not head or not head . next :
return head
mid = self . middleNode (head)
left = self . sortList (head)
right = self . sortList (mid)
return self . mergeTwoLists (left, right)