"""Definition of ListNodeclass ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next"""classSolution:""" @param head: The first node of the linked list. @return: You should return the head of the sorted linked list, using constant space complexity. """defsortList(self,head):# write your code hereifhead==Noneorhead.next==None:returnhead# Find the pivotdummy_node=ListNode(0,None)dummy_node.next=headpivot=dummy_nodefast_node=dummy_nodewhilefast_node!=Noneandfast_node.next!=None:fast_node=fast_node.next.nextpivot=pivot.nextpivot.next=Nonel1=headl2=pivot.next# This is for l1. Make sure l1 is terminatedpivot.next=Nonereturnself.mergeTwoLists(self.sortList(l1),self.sortList(l2))defmergeTwoLists(self,l1,l2):ifl1==Noneandl2==None:returnNoneifl1==Noneandl2!=None:returnl2ifl1!=Noneandl2==None:returnl1# Dummy Noderesult=ListNode(-1,None)head=resultwhilel1!=Noneandl2!=None:ifl1.val<=l2.val:head.next=l1l1=l1.nextelse:head.next=l2l2=l2.nexthead=head.next# l1 or l2 is not donewhilel1!=None:head.next=l1l1=l1.nexthead=head.nextwhilel2!=None:head.next=l2l2=l2.nexthead=head.nextreturnresult.next