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)


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

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




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

相关推荐
川石课堂软件测试4 分钟前
Python | 高阶函数基本应用及Decorator装饰器
android·开发语言·数据库·python·功能测试·mysql·单元测试
吃着火锅x唱着歌19 分钟前
LeetCode 2016.增量元素之间的最大差值
数据结构·算法·leetcode
Naiva32 分钟前
【小技巧】PyCharm建立项目,VScode+CodeX+WindowsPowerShell开发Python pyQT6
vscode·python·pycharm
nvd1144 分钟前
asyncio.run() vs asyncio.gather():启动器与聚合器, 为何Jupyter notebook里能直接使用await?
开发语言·python·jupyter
EEG小佬1 小时前
Jupyter选择内核时如何找到虚拟环境
ide·python·jupyter
文人sec1 小时前
使用python-pandas-openpyxl编写运营查询小工具
开发语言·python·pandas
hu_yuchen1 小时前
问卷系统自动化测试报告
软件测试·python
百锦再2 小时前
第8章 模块系统
android·java·开发语言·python·ai·rust·go
Ashlee_code2 小时前
经纪柜台系统解析:从今日国际金融动荡看证券交易核心引擎的变革
python·架构·系统架构·区块链·vim·柜台·香港券商
清空mega2 小时前
从零开始搭建 flask 博客实验(4)
后端·python·flask