印象中,这是遍历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
#初始dummy
dummy=ListNode(0,next=head)
p0=dummy
#先走到left左边那个
for i in range(left-1):
p0=p0.next
#经典反转算法
pre=None
cur=p0.next
#right-left+1个元素
for j in range(right-left+1):
nxt=cur.next
cur.next=pre
#向后移动
pre=cur
cur=nxt
#反转后的left~right段应该和原链表相连接
p0.next.next=cur
p0.next=pre
return dummy.next
ps:
跟灵神学算法