印象中,这是遍历r2了,还好没放弃。
# 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]:#首次创建一个dummy结点,防止left是第一个结点,即没有p0#关键结点顺序应该为p0,pre,cur,nxt#初始dummydummy=ListNode(0,next=head)p0=dummy#先走到left左边那个for i in range(left-1):p0=p0.next#经典反转算法pre=Nonecur=p0.next#right-left+1个元素for j in range(right-left+1):nxt=cur.nextcur.next=pre#向后移动pre=curcur=nxt#反转后的left~right段应该和原链表相连接p0.next.next=curp0.next=prereturn dummy.next
ps:
跟灵神学算法