leetcode 92. 反转链表 II 区间反转(不是整条链表反转)

  1. 找到区间的pre、left、right、nxt,保存
  2. 区间反转
  3. pre.next 连接新头(right)
  4. 区间尾巴(原来的left)接上nxt
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]:

        # 1. 找区间的pre、next 节点

        pre = ListNode(0)
        pre.next = head
        dummy = pre

        for i in range(left-1):
            pre = pre.next
        # 此时pre.next = 区间头节点
        left_node = pre.next

        right_node = head
        for i in range(right-1):
            right_node = right_node.next

        # 2. 反转区间
        cur = left_node

        # 断首尾
        prev = ListNode(0)
        prev.next = left_node   # 给个暂时的节点,指向区间left
        nxt = right_node.next    # 保存原始区间next

        while cur != nxt:  # 结束时cur已经出区间了,这样区间内才反转完
            tmp = cur.next  # 保存原始区间next
            cur.next = prev
            prev = cur
            cur = tmp

        pre.next = right_node  # 原来的区间pre_node 指向原来的尾节点(现在的left)
        left_node.next = nxt  # 现在的尾节点(原来的left)指向保存好的nxt

        return dummy.next        
相关推荐
Navigator_Z13 小时前
LeetCode //C - 1320. Minimum Distance to Type a Word Using Two Fingers
c语言·算法·leetcode
wy_hhxx1 天前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
AIgorithmGEEK1 天前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash
Navigator_Z1 天前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
Navigator_Z2 天前
LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c
c语言·算法·leetcode
驭渊的小故事2 天前
LeetCode 33:搜索旋转排序数组——从二分查找到旋转数组的区间判定
算法·leetcode·职场和发展
2401_858286113 天前
LKDS8.Linux内核的双向链表代码解析(8) 拼接链表、获取链表首/尾元素的宏、list_for_each系列的安全版本的宏
linux·链表
郝学胜-神的一滴3 天前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
CoderYanger3 天前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
Navigator_Z3 天前
LeetCode //C - 1323. Maximum 69 Number
c语言·算法·leetcode