力扣:92. 反转链表 II(Python3)

题目:

给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。

来源:力扣(LeetCode)
链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

示例:

示例 1:

力扣:92. 反转链表 II(Python3)_第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: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        list1 = []
        while head:
            list1.append(head.val)
            head = head.next
        list1 = list1[:left - 1] + list1[left - 1: right][::-1] + list1[right:]
        head = point = ListNode()
        for num in list1:
            point.next = ListNode(num)
            point = point.next
        return head.next

你可能感兴趣的:(LeetCode,leetcode,算法,python)