mycode    97.37%

如果用上一个题目中”参考“的方法,res中放节点而不是val,就会超时

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        res = []
        while head:
            res.append(head.val)
            head = head.next
        res.sort()
        
        dummy = head = ListNode(-1)
        for l in res:
            head.next = ListNode(l)
            head = head.next
        return dummy.next
            

 

参考 

二分法!!!!!!!

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def sortList(self, head):
        if not head or not head.next:
            return head
        slow, fast = head, head.next
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        second = slow.next
        slow.next = None
        first_half = self.sortList(head)
        second_half = self.sortList(second)
        return self.merge(first_half, second_half)

    def merge(self,l1, l2):
        if not l1 or not l2:
            return l2 or l1
        s, e = None, None
        while l1 and l2:
            if l1.val > l2.val:
                if not s:
                    s = e = l2
                    l2 = l2.next
                else:
                    e.next = l2
                    e = e.next
                    l2 = l2.next
            else:
                if not s:
                    s = e = l1
                    l1 = l1.next
                else:
                    e.next = l1
                    e = e.next
                    l1 = l1.next
        e.next = l1 or l2
        return s