反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
1. 思路
2. 代码
# 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: ListNode, left: int, right: int) -> ListNode:
if not head:return None
if left == right:return head
pre = None
tail = None
reverse_start = head
reverse_end = head
# 第一步,保存断链后的前驱pre
for i in range(left-1):
pre = reverse_start
if reverse_start.next:
reverse_start = reverse_start.next
reverse_end = reverse_end.next
else:
return None
# 第二步,确定要反转的链表
for i in range(right-left):
if reverse_end:
reverse_end = reverse_end.next
else:
return None
tail = reverse_end.next
# 第三步,断链
if pre:
pre.next = None
reverse_end.next = None
# 第四步,反转链表
def reverse_list(head):
q = head.next
head.next = None
while q:
tmp = q.next
q.next = head
head = q
q = tmp
return head
# pre为None表示left为第一个元素
if pre:
pre.next = reverse_list(reverse_start)
else:
head = reverse_list(reverse_start)
# reverse_start反转链表部分的最后一个元素,reverse_start=None
if tail:
reverse_start.next = tail
return head