# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @return {ListNode} def sortList(self, head): def _megSort(head, length): if length<=1: return head p=head subLen=0 for _ in range((length-1)/2): p=p.next subLen+=1 q=p.next p.next=None La=_megSort(head, subLen) Lb=_megSort(q, length-subLen) return _merge(La, Lb) def _merge(p, q): d=ListNode(-1) r=d while p and q: if p.val<q.val: r.next=p r=p p=p.next else: r.next=q r=q q=q.next while p: r.next=p r=p p=p.next while q: r.next=q r=q q=q.next return d.next p=head length=0 while p: length+=1 p=p.next return _megSort(head, length)