Sort List

题目描述

Sort a linked list in O(n log n) time using constant space complexity.

解题方法

Solution

# 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
        """
        if not head or not head.next:
            return head
        p1 = head
        p2 = head
        while p2.next and p2.next.next:
            p1 = p1.next
            p2 = p2.next.next

        #first half
        head1 = head
        #second half
        head2 = p1.next
        p1.next = None
        leftList = self.sortList(head1)
        rightList = self.sortList(head2)
        return self.merge(leftList, rightList)

    def merge(self, list1, list2):
        dummy = ListNode(0)
        pre = dummy
        while list1 and list2:
            if list1.val < list2.val:
                pre.next = list1
                list1 = list1.next
            else:
                pre.next = list2
                list2 = list2.next
            pre = pre.next
        if list1:
            pre.next = list1
        if list2:
            pre.next = list2
        return dummy.next

Reference