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
相关推荐
Tech Synapse26 分钟前
基于Surprise和Flask构建个性化电影推荐系统:从算法到全栈实现
python·算法·flask·协同过滤算法
終不似少年遊*34 分钟前
国产之光DeepSeek架构理解与应用分析04
人工智能·python·深度学习·算法·大模型·ds
天天扭码34 分钟前
一分钟解决 | 高频面试算法题——最大子数组之和
前端·算法·面试
杰杰批39 分钟前
力扣热题100——矩阵
算法·leetcode·矩阵
明月看潮生42 分钟前
青少年编程与数学 02-016 Python数据结构与算法 28课题、图像处理算法
图像处理·python·算法·青少年编程·编程与数学
_GR1 小时前
2025年蓝桥杯第十六届C&C++大学B组真题及代码
c语言·数据结构·c++·算法·贪心算法·蓝桥杯·动态规划
心想事“程”1 小时前
决策树详解+面试常见问题
算法·决策树·机器学习
照海19Gin2 小时前
数据结构中的宝藏秘籍之广义表
c语言·数据结构·算法
小oo呆3 小时前
【自然语言处理与大模型】模型压缩技术之剪枝
算法·机器学习·剪枝
bloxd yzh3 小时前
筛选法(埃氏筛法)C++
数据结构·算法