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
相关推荐
一匹电信狗21 分钟前
【C++】手搓AVL树
服务器·c++·算法·leetcode·小程序·stl·visual studio
月疯23 分钟前
离散卷积,小demo(小波信号分析)
算法
敲代码的瓦龙1 小时前
西邮移动应用开发实验室2025年二面题解
开发语言·c++·算法
RTC老炮1 小时前
webrtc弱网-RembThrottler类源码分析及算法原理
网络·算法·webrtc
野蛮人6号2 小时前
力扣热题100道之73矩阵置零
算法·leetcode·矩阵
野蛮人6号2 小时前
力扣热题100道之238除自身以外数组的乘积
算法·leetcode·职场和发展
坚持编程的菜鸟2 小时前
LeetCode每日一题——缀点成线
c语言·算法·leetcode
小梁努力敲代码2 小时前
java数据结构--LinkedList与链表
java·数据结构·链表
派大星爱吃猫2 小时前
直接插入排序详解
算法·排序算法·直接插入排序
qq_433554542 小时前
C++ 双向循环链表
开发语言·c++·链表