leetcode-148. 排序链表

题目描述

给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表

示例 1:

复制代码
输入:head = [4,2,1,3]
输出:[1,2,3,4]

示例 2:

复制代码
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]

示例 3:

复制代码
输入:head = []
输出:[]

思路

使用快慢指针完成+合并两个有序链表完成归并排序

python 复制代码
# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution(object):
    def sortFunc(self, head, tail):
        if not head:
            return head
        if head.next == tail:
            head.next = None
            return head
        slow = fast = head
        while fast != tail:
            slow = slow.next
            fast = fast.next
            if fast != tail:
                fast = fast.next
        mid = slow
        return self.merge(self.sortFunc(head, mid), self.sortFunc(mid, tail))

    def merge(self, head1, head2):
        pre = ListNode(-1)
        head, head1, head2 = pre, head1, head2
        while head1 and head2:
            if head1.val <= head2.val:
                head.next = head1
                head1 = head1.next
            else:
                head.next = head2
                head2 = head2.next
            head = head.next
        if head1:
            head.next = head1
        if head2:
            head.next = head2
        return pre.next

    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        return self.sortFunc(head, None)

if __name__ == '__main__':
    s = Solution()
    head = ListNode(1)
    phead = head
    data = [4, 3, 7, 5] 
    for i in data:
        node = ListNode(i)
        phead.next = node
        phead = phead.next
    head = s.sortList(head)
    while head:
        print(head.val),
        head = head.next
相关推荐
fie888919 小时前
NSCT(非下采样轮廓波变换)的分解和重建程序
算法
晨晖220 小时前
单链表逆转,c语言
c语言·数据结构·算法
YoungHong199221 小时前
面试经典150题[072]:从前序与中序遍历序列构造二叉树(LeetCode 105)
leetcode·面试·职场和发展
im_AMBER1 天前
Leetcode 78 识别数组中的最大异常值 | 镜像对之间最小绝对距离
笔记·学习·算法·leetcode
鼾声鼾语1 天前
matlab的ros2发布的消息,局域网内其他设备收不到情况吗?但是matlab可以订阅其他局域网的ros2发布的消息(问题总结)
开发语言·人工智能·深度学习·算法·matlab·isaaclab
LYFlied1 天前
【每日算法】LeetCode 25. K 个一组翻转链表
算法·leetcode·链表
Swizard1 天前
别再迷信“准确率”了!一文读懂 AI 图像分割的黄金标尺 —— Dice 系数
python·算法·训练
s09071361 天前
紧凑型3D成像声纳实现路径
算法·3d·声呐·前视多波束
可爱的小小小狼1 天前
算法:二叉树遍历
算法
d111111111d1 天前
在STM32函数指针是什么,怎么使用还有典型应用场景。
笔记·stm32·单片机·嵌入式硬件·学习·算法