给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例 1:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
示例 2:
输入:head = [5], left = 1, right = 1
输出:[5]
# 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
head = ListNode(0,head)
position = 0
begin_point, end_point = None, None #初始化剪切点
pointer = head
while(pointer):
if position + 1 == left:
begin_point = pointer #保存剪切点
elif position == right:
before_end_point = pointer
if (pointer.next):
end_point = pointer.next #保存剪切点
position += 1
pointer = pointer.next
pointer = begin_point.next
position = 0
begin_point.next = before_end_point #左侧与反转链右侧
reverse_list = end_point #右侧反转链左侧
for p in range(right-left+1):
if (pointer):
temp = pointer.next
pointer.next = reverse_list
reverse_list = pointer
pointer = temp
return head.next
妈呀这题真的花了我好久的时间
不过最后的结果还是很满意的
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii