跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客我的书AI学习GitHub 精选镜像AI 生图工具UI配色美学关于
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
Python算法

链表算法实战:反转、合并与排序(Python)

链表算法实战涵盖基础反转、区间反转及分组翻转。通过快慢指针定位中间节点实现归并排序,结合双指针合并有序链表完成整体排序。提供 Python 代码示例,包含哨兵节点优化逻辑,解决 LeetCode 经典链表问题。

道系青年发布于 2026/3/16更新于 2026/10/18107 浏览
链表算法实战:反转、合并与排序(Python)

链表算法实战:反转、合并与排序(Python)

一、链表反转

1.1 反转链表

Python 代码
from typing import Optional

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        pre = None
        cur = head
        while cur:
            nxt = cur.next
            cur.next = pre
            pre = cur
            cur = nxt
        return pre

1.2 反转链表 II

思路

整体来看,p0 是反转前的第 left 个节点的前驱,pre 是反转后的头节点,cur 是当前遍历到的节点。

Python 代码
class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        p0 = dummy = ListNode(next=head)
        for _ in range(left - 1):
            p0 = p0.next
        pre = None
        cur = p0.next
        for _ in range(right - left + 1):
            nxt = cur.next
            cur.next = pre
            pre = cur
            cur = nxt
        p0.next.next = cur
        p0.next = pre
        return dummy.next

1.3 K 个一组翻转链表

Python 代码
class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        n = 0
        cur = head
        while cur:
            n += 1
            cur = cur.next
        
        p0 = dummy = ListNode(next=head)
        pre = None
        cur = head
        
        while n >= k:
            n -= k
            for _ in range(k):
                nxt = cur.next
                cur.next = pre
                pre = cur
                cur = nxt
            nxt = p0.next
            nxt.next = cur
            p0.next = pre
            p0 = nxt
        return dummy.next

二、链表排序

2.1 链表的中间结点

思路

典型的快慢指针法。t1 每次走一步,t2 每次走两步,当 t2 到达末尾时,t1 即为中间节点。

Python 代码
class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        t1 = t2 = head
        while t2 and t2.next:
            t1 = t1.next
            t2 = t2.next.next
        return t1

2.2 合并两个有序链表

Python 代码
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        cur = dummy = ListNode()
        while list1 and list2:
            if list1.val <= list2.val:
                cur.next = list1
                cur = cur.next
                list1 = list1.next
            else:
                cur.next = list2
                cur = cur.next
                list2 = list2.next
        cur.next = list1 if list1 else list2
        return dummy.next

2.3 排序链表

思路

归并排序。找到链表的中间节点,断开为前后两端,分别排序前后两端,排序后再合并两个有序链表。

Python 代码
class Solution:
    # 876. 链表的中间结点(快慢指针)
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = fast = head
        while fast and fast.next:
            pre = slow
            slow = slow.next
            fast = fast.next.next
        pre.next = None
        return slow

    # 21. 合并两个有序链表(双指针)
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        cur = dummy = ListNode()
        while list1 and list2:
            if list1.val < list2.val:
                cur.next = list1
                list1 = list1.next
            else:
                cur.next = list2
                list2 = list2.next
            cur = cur.next
        cur.next = list1 if list1 else list2
        return dummy.next

    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head is None or head.next is None:
            return head
        head2 = self.middleNode(head)
        head = self.sortList(head)
        head2 = self.sortList(head2)
        return self.mergeTwoLists(head, head2)

目录

  1. 链表算法实战:反转、合并与排序(Python)
  2. 一、链表反转
  3. 1.1 反转链表
  4. Python 代码
  5. 1.2 反转链表 II
  6. 思路
  7. Python 代码
  8. 1.3 K 个一组翻转链表
  9. Python 代码
  10. 二、链表排序
  11. 2.1 链表的中间结点
  12. 思路
  13. Python 代码
  14. 2.2 合并两个有序链表
  15. Python 代码
  16. 2.3 排序链表
  17. 思路
  18. Python 代码

更多推荐文章

查看全部
  • 网络安全零基础入门学习路线与规划指南
  • Kali Linux 2025.4 发布:Wayland 默认、桌面与工具链更新
  • Quilter:基于物理驱动的 AI 电路板设计工具
  • VSCode 登录 GitHub 报错“尚未完成授权”的解决方法
  • Qwen3-VL 基于 Llama-Factory 的 QLoRA 微调与部署全流程实战
  • 基于 MCP 协议的图片素描风格转换工具使用指南
  • 二分查找算法简介及在排序数组中查找元素的首尾位置
  • Linux 互斥锁原理与 C++ RAII 封装实战
  • 修复 Microsoft Visual C++ 2022 X86 Minimum Runtime 安装错误
  • Python 库 adaptnlp 语法、参数及实际应用案例
  • Trae + Git 本地仓库管理 (离线) 小白指南
  • 华为昇腾 CANN:全场景 AI 计算基础软件平台解析
  • Kubernetes 云原生实践:.NET Core 与 Java 深度对比与选型
  • 转行网络安全两年的真实经验与建议
  • 2024 年 AI 绘画现状分析:Midjourney 与 Stable Diffusion 实用价值探讨
  • VR-Reversal 插件实现 3D 视频转 2D 格式教程
  • Python 构建 AI 三工具:文档总结、代码生成与智能检索
  • Live Avatar 部署教程:Gradio Web UI 与 CLI 模式快速上手
  • 基于 ESP32-S3 芯片的 Wi-Fi 智能机器人系统设计
  • Windows 环境 LLaMA-Factory 本地部署教程:从零搭建大模型工具链

相关免费在线工具

  • 加密/解密文本

    使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online

  • Gemini 图片去水印

    基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online

  • curl 转代码

    解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online

  • Markdown转HTML

    将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online