链表 | 快速排序 | 归并排序:力扣148. 排序链表

1、题目描述:

链表 | 快速排序 | 归并排序:力扣148. 排序链表_第1张图片

2、题解:

方法1:归并排序
思路:

1、先处理特殊情况
2、然后从中间切分,用快慢指针找到中间值进行递归
3、合并两个有序的链表

Python代码如下:

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

class Solution:
    def sortList(self, head: ListNode) -> ListNode:
        #归并排序
        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
        mid,slow.next = slow.next,None
        #递归的进行左边和右边排序
        left,right = self.sortList(head),self.sortList(mid)
        #合并两个有序的链表
        p = res = ListNode(0)
        while left and right:
            if left.val < right.val:
                p.next,left = left,left.next
            else:
                p.next,right = right,right.next
            p = p.next
        p.next = left if left else right
        return res.next

方法2:快速排序
Python超时
思路:

先用双指针进行划分链表
然后先排右边的,再排左边的,然后拼接左右两边的
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def sortList(self, head: ListNode) -> ListNode:
        #快速排序
        def qucikSort(head):
            if not head or not head.next:
                return head
            pivot = head.val
            #链表划分
            left_node ,right_node = ListNode(0),ListNode(0)
            p1,p2 = left_node,right_node
            cur = head
            while cur:
                if cur.val < pivot:
                    p1.next = cur
                    p1 = p1.next
                else:
                    p2.next = cur
                    p2 = p2.next
                cur = cur.next
            p1.next = right_node.next
            p2.next = None
            #递归调用,先重排右边的,再把指针置空,再重排左边的
            right = qucikSort(head.next)
            head.next = None
            left = qucikSort(left_node.next)
            #拼接左半部分和右半部分
            cur = left
            while cur.next:
                cur = cur.next
            cur.next = right
            return left
        return qucikSort(head)

3、复杂度分析:

你可能感兴趣的:(LeetCode)