思路:
1.left==right,返回原链表
2.left <> right,添加虚拟头结点
3.保存子链表的前一个指针和后一个指针,用于拼接反转后的子链表。
# 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 left == right:
return head
# 不相等,则反转子链表,可能会改变头结点,添加虚拟头结点
dummy = ListNode()
dummy.next = head
cur = dummy
count = 1
while cur!=None:
# 保存切断前的指针
if count == left:
first = cur
lhead = cur.next
if count == right + 1:
# 保存切断后的指针
second = cur.next
# 反转链表,比如2,3,4,lhead表示指向2,cur指向4
lhead,lend = self.ReverseList(lhead,cur.next)
# 拼接
# 切断前的指针指向反转后的头结点
first.next = lhead
# 反转后的尾结点指向切断后的指针
lend.next = second
return dummy.next
count = count + 1
cur = cur.next
# 反转链表
def ReverseList(self, head, end):
if not head or not head.next:
return head
cur = head
last = None
# 当cur为空时,last指向了最后一个节点
while True:
#先用tmp保存cur的下一个节点的信息,
tmp = cur.next
# 改变指向前一个节点
cur.next = last
#让last,cur依次向后移动一个节点,继续下一次的指针反转
last = cur
cur = tmp
if cur == end:
break
return last, head
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)