实现单链表的归并排序python

版权声明:本文为博主原创文章,转载请附上本博文链接。 https://blog.csdn.net/weixin_41704182/article/details/87569080

示例:7-> 5-> 4 ->8-> 3-> 6-> 2 ->1 ->9

  1. 找出中间位置,拆分成左右子链,对于链表,我们可以使用快慢指针确定中点。
    7->5->4->8 ; 3->6->2->1->9

  2. 对拆分的子链在进行拆分,直到拆分成单个或2个元素。
    7->5 ; 4->8 ; 3->6 ; 2->1 ; 9

  3. 逆照拆分顺序,对分开的元素进行第一次组合排序。
    5->7 ; 4->8 ;3->6 ;1->2 ; 9

  4. 逆照拆分顺序,对分开的元素进行第二次组合排序。
    4->5->7->8 ;1->2->3->6 ; 9

  5. 逆照拆分顺序,对分开的元素进行排序,直至剩下两个子链。
    4->5->7->8 ;1->2->3->6->9

  6. 创建新链,不断对比两个链中最小的元素,并把最小的元素放进新链中,如果其中一个新链空了,就在新链中追加另一条链的元素,直至两条链都为空。
    1->2->3->4->5->6->7->8->9

排序算法代码如下

#定义节点
class ListNode(object):
    def __init__(self, val, next=None):
        self.val = val
        self.next = next

def sort(phead):
    if phead == None or phead.next == None:
        return phead
    tmp = phead
    slow = phead  # 使用快慢指针来确定中点
    fast = phead
    while fast and fast.next:
        tmp = slow
        slow = slow.next
        fast = fast.next.next

    left = phead
    right = tmp.next
    tmp.next = None  # 对拆链表
    left = sort(left)
    right = sort(right)
    return merge(left, right)

def merge(left, right):
    tmp = ListNode(-1)
    newhead = tmp   #创建新链表
    while left and right:
        if left.val < right.val:
            tmp.next = left
            tmp = left
            left = left.next
        else:
            tmp.next = right
            tmp = right
            right = right.next
    if left:
        tmp.next = left
    else:
        tmp.next = right
    return newhead.next

猜你喜欢

转载自blog.csdn.net/weixin_41704182/article/details/87569080
今日推荐