LeetCode-92. 反转链表 II【链表】

LeetCode-92. 反转链表 II【链表】

题目描述:

给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。

示例 1:

输入:head = 1,2,3,4,5, left = 2, right = 4

输出:1,4,3,2,5

示例 2:

输入:head = 5, left = 1, right = 1

输出:5

提示:

链表中节点数目为 n

1 <= n <= 500

-500 <= Node.val <= 500

1 <= left <= right <= n

解题思路一:简单的翻转链表操作

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
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

时间复杂度:O(n)

空间复杂度:O(1)

背诵版:

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
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

时间复杂度:O(n)

空间复杂度:O(1)

解题思路三:0

python 复制代码

时间复杂度:O(n)

空间复杂度:O(n)


创作不易,观众老爷们请留步... 动起可爱的小手,点个赞再走呗 (๑◕ܫ←๑) 欢迎大家关注笔者,你的关注是我持续更博的最大动力

原创文章,转载告知,盗版必究




♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠

相关推荐
江华森2 分钟前
Python 实现 2048 游戏(三):面向对象重构与AI模拟
python
可以飞的话35 分钟前
五、数据处理1
python
鱼毓屿御37 分钟前
Python 装饰器与函数调用机制(复习笔记 · 2026-07-07)
开发语言·python
AC赳赳老秦1 小时前
采购专员自动化:OpenClaw 自动比价、生成询价单、跟踪供应商报价进度实战指南
开发语言·数据库·人工智能·python·自动化·github·openclaw
ednO8nqdR1 小时前
Python小游戏制作:如何实现可配置的跨分辨率界面布局
python·plotly·django·virtualenv·scikit-learn·fastapi·pygame
tachibana21 小时前
hot100 排序链表(148)
java·数据结构·算法·leetcode·链表
林泽毅1 小时前
Qwen3.5 DPO 模型对齐实战(pytrio训练版)
人工智能·python·算法
荣码1 小时前
LangGraph多步工作流:Agent不够用的时候,我踩了4个坑
java·python
曲幽2 小时前
从卡顿到丝滑:FastAPI 调用外部 API 的正确姿势(httpx 实战)
python·fastapi·web·async·httpx·client·await·requests·aiohttp
不能跑的代码不是好代码2 小时前
二叉树从基础概念到LeetCode实战
算法·leetcode