# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = NoneclassSolution(object):defsortList(self,head):""" :type head: ListNode :rtype: ListNode """ifhead==Noneorhead.next==None:returnheadslow=headfast=headwhilefast.nextandfast.next.next:slow=slow.nextfast=fast.next.nextright=slow.nextleft=headslow.next=None# use slow and fast cursor to split into 2 partsleft=self.sortList(left)right=self.sortList(right)head=self.merge(left,right)returnheaddefmerge(self,left,right):ifleft==None:returnrightifright==None:returnleft# O(1) space, insert right into leftifleft.val<=right.val:result=leftleft=left.nextelse:result=rightright=right.nexttmp=resultwhileleftandright:ifleft.val<=right.val:tmp.next=leftleft=left.nexttmp=tmp.nextelse:tmp.next=rightright=right.nexttmp=tmp.nextifleft==None:tmp.next=rightifright==None:tmp.next=leftreturnresult
近期评论