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
相关推荐
万物智能17 分钟前
PWM散热风扇设置—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
前端·后端·算法
北极有牛31 分钟前
cuda算子--矩阵转置
人工智能·算法
程序猫.1 小时前
算法刷题笔记:模拟题从入门到实战(含 LeetCode 例题与习题)
java·数据结构·算法
liliangcsdn1 小时前
zpos因果对冲的分析和示例
算法
Shan12051 小时前
经典算法题学习:跳跃游戏IV(一)
算法
AIGCmagic社区1 小时前
灵巧手VLA真机均分71%,北大DeCAL用接触门控接入触觉
人工智能·算法·aigc·ai多模态
迷途之人不知返2 小时前
算法系列4:前缀和
算法
吠品2 小时前
Python 写入 Excel 的两种主流方案实际用法总结
c语言·开发语言·算法
Zane19942 小时前
归并排序和堆排序都能保证O(nlogn),为什么谁也没法把稳定和原地两个优点占全
算法·排序算法
天天喝旺仔2 小时前
Go 泛型实战:从类型参数、约束到可复用泛型容器与函数
数据结构·算法·容器·go