LeetCode148:Sort List

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

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

LeetCode:链接

归并排序:参考1   LeetCode21: Merge Two Sorted Lists    

由于题目对时间复杂度和空间复杂度要求比较高,最好的解法就是归并排序。

用归并排序的思想,将链表用快慢指针分成两半,然后两半排好序,最后归并。

这里涉及到一个链表常用的操作,即快慢指针的技巧。设置slow和fast指针,开始它们都指向表头,fast每次走两步,slow每次走一步,fast到链表尾部时,slow正好到中间,这样就将链表截为两段

# 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
        slow, fast = head, head
        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
        head1 = head
        # 新表头
        head2 = slow.next
        # 将一个链表分开
        slow.next = None 
        head1 = self.sortList(head1)
        head2 = self.sortList(head2)
        head = self.merge(head1, head2)
        return head

    def merge(self, head1, head2):
        if not head1:
            return head2
        if not head2:
            return head1
        # 哨兵机制
        dummy = ListNode(0)
        p = dummy
        while head1 and head2:
            if head1.val <= head2.val:
                p.next = head1
                head1 = head1.next
            else:
                p.next = head2
                head2 = head2.next
            p = p.next
        if not head1:
            p.next = head2
        if not head2:
            p.next = head1
        return dummy.next

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/85622091