Python | Leetcode Python题解之第148题排序链表

题目:

题解:

class Solution:
    def sortList(self, head: ListNode) -> ListNode:
        def merge(head1: ListNode, head2: ListNode) -> ListNode:
            dummyHead = ListNode(0)
            temp, temp1, temp2 = dummyHead, head1, head2
            while temp1 and temp2:
                if temp1.val <= temp2.val:
                    temp.next = temp1
                    temp1 = temp1.next
                else:
                    temp.next = temp2
                    temp2 = temp2.next
                temp = temp.next
            if temp1:
                temp.next = temp1
            elif temp2:
                temp.next = temp2
            return dummyHead.next
        
        if not head:
            return head
        
        length = 0
        node = head
        while node:
            length += 1
            node = node.next
        
        dummyHead = ListNode(0, head)
        subLength = 1
        while subLength < length:
            prev, curr = dummyHead, dummyHead.next
            while curr:
                head1 = curr
                for i in range(1, subLength):
                    if curr.next:
                        curr = curr.next
                    else:
                        break
                head2 = curr.next
                curr.next = None
                curr = head2
                for i in range(1, subLength):
                    if curr and curr.next:
                        curr = curr.next
                    else:
                        break
                
                succ = None
                if curr:
                    succ = curr.next
                    curr.next = None
                
                merged = merge(head1, head2)
                prev.next = merged
                while prev.next:
                    prev = prev.next
                curr = succ
            subLength <<= 1
        
        return dummyHead.next

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-13 16:18:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-13 16:18:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-06-13 16:18:02       87 阅读
  4. Python语言-面向对象

    2024-06-13 16:18:02       96 阅读

热门阅读

  1. 如何通过Python爬虫提升电商数据分析效率

    2024-06-13 16:18:02       35 阅读
  2. 新需求:实现一个自动运维部署工具

    2024-06-13 16:18:02       27 阅读
  3. 编程里len是什么意思:深度解析与应用探讨

    2024-06-13 16:18:02       27 阅读
  4. 【DPDK学习路径】五、线程创建及核心绑定

    2024-06-13 16:18:02       30 阅读
  5. 浅拷贝与深拷贝全面解析及实战

    2024-06-13 16:18:02       28 阅读
  6. js点击切换的轮播图

    2024-06-13 16:18:02       31 阅读
  7. 使用 ftrace 进行内核跟踪

    2024-06-13 16:18:02       45 阅读
  8. 使用canvas制作一个无人机旋转特效

    2024-06-13 16:18:02       26 阅读
  9. Linux使用过程中的一些技巧

    2024-06-13 16:18:02       22 阅读
  10. 僵尸进程与孤儿进程

    2024-06-13 16:18:02       25 阅读
  11. PyTorch -- 最常见损失函数 LOSS 的选择

    2024-06-13 16:18:02       29 阅读