LintCode 98. Sort List

题目

LintCode 98. Sort List_第1张图片

思路

归并排序,链表。

代码

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""


class Solution:
    """
    @param: head: The head of linked list.
    @return: You should return the head of the sorted linked list, using constant space complexity.
    """
    def findMid(self, head):
        slow = head
        fast = head
        pre = ListNode(0)
        pre.next = head
        while fast and fast.next:
            slow = slow.next
            pre = pre.next
            fast = fast.next.next
        pre.next = None
        return slow
    def merge(self, head1, head2):
        dummy = ListNode(0)
        node = dummy
        while head1 and head2:
            if head1.val < head2.val:
                node.next = head1
                node = node.next
                head1 = head1.next
            else:
                node.next = head2
                node = node.next
                head2 = head2.next
        while head1:
            node.next = head1
            node = node.next
            head1 = head1.next
        while head2:
            node.next = head2
            node = node.next
            head2 = head2.next
        # node.next = None
        return dummy.next 
    def mergeSort(self, head):
        mid = self.findMid(head)
        if mid == head: return head
        left = self.mergeSort(head)
        right = self.mergeSort(mid)
        return self.merge(left, right)
    def sortList(self, head):
        # write your code here
        if not head: return None
        return self.mergeSort(head)

你可能感兴趣的:(OJ-LintCode,算法-链表)