题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
# class ListNode:
# 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
# 加个表头
res=ListNode(-1) # 头节点之前的位置
res.next=head
# 前序节点
pre=res
# 当前节点
cur=head
# 找到m位置
for i in range(1,m):
pre,cur=cur,cur.next # pre cur 往后移
# 此时 pre是位置m-1 cur是位置m
# 反转之后,m在最后一个(cur往后移),n接在pre之后
for i in range(m,n): # cur锚定在2上,不再改变
a=cur.next # 2的下一个是3
cur.next=a.next # 2与(3的下一个)4连接 2-->4
a.next=pre.next # 3与2连接 3-->2
pre.next=a # 1 与 3 连接 1-->3
# 1-->3-->2-->4-->5
# 1-->4-->3-->2-->5
return res.next
# b,a,a.next=b.next,b,a

查看24道真题和解析