leetcode刷题笔记-merge sort

这篇博客记录了作者在研一上学期学习归并排序时,针对LeetCode 148题——排序链表的解题笔记,将链表排序问题与归并排序算法结合进行探讨。
摘要由CSDN通过智能技术生成

Merge sort我研一上学期时候的笔记:

148. Sort List

简直就是我的笔记的代码版本。

# 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 head is None or head.next is None:
            return head
        
        # step1 cut the list into two halves
        prev, slow, fast = None, head, head
        while fast is not None and fast.next is not None:
            prev = slow
            slow = slow.next
            fast = fast.next.next
        
        # break to two halves
        prev.next = None
        
        # step2 sort each half
        left = self.sortList(head)
        right = self.sortList(slow)
        
        return self.merge(left, right)
    
    def merge(self, left, right):
        l = ListNode(0)
        p = l
        
        while left is not None and right is not None:
            if left.val < right.val:
                p.next = left
                left = left.next
            else:
                p.next = right
                right = right.next
            
            p = p.next
        
        if left is not None:
            p.next = left
        if right is not None:
            p.next = right
        return l.next

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值