题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
# class ListNode:
# from numpy._typing import _NBitLongDouble
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @param m int整型
# @param n int整型
# @return ListNode类
#
class Solution:
def reverseBetween(self , head: ListNode, m: int, n: int) -> ListNode:
# write code here
if not head:
return
# 头插法虚拟节点
dummy_head = ListNode(0)
# 头插法
count = 1
temp = dummy_head #这里主要是记录变化
temp2 = ListNode(0) # 这个用来记录倒序的开始节点
# 主要想法是: 把head逐个节点复制下来,当需要倒叙的时候(如题目中链条2-3-4),记录下当前倒叙节点(如temp2=2);把需要倒叙的链条转换(转换后4-3-2);转换后的最后节点为已经记录的temp2,所以从此之后继续逐个复制。
while head:
if count >= m and count <=n:
# 提前记录
tmp = head
head = head.next
# 将当前节点在头部插入
tmp.next = temp.next
temp.next = tmp
if count == m:
temp2 = tmp
if count == n:
temp = temp2
# for i in range(n-m+1):
# temp = temp.next
else:
new_node = ListNode(head.val)
temp.next = new_node
temp = new_node
head = head.next
# temp = temp.next
count = count + 1
# dummy_head = temp
return dummy_head.next
查看8道真题和解析
美的集团公司福利 717人发布