92. 反转链表 II_CodingPark编程公园
作者:互联网
反转链表 II
问题
给你单链表的头指针 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]
提示:
链表中节点数目为 n
1 <= n <= 500
-500 <= Node.val <= 500
1 <= left <= right <= n
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
解答
que2.reverse() 反转部分列表内容
# 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:
que1 = []
while head:
que1.append(head.val)
head = head.next
que2 = que1[left-1:right]
que2.reverse()
res = que1[:left-1]+que2+que1[right:]
ping = cur = ListNode()
for i in res:
cur.next = ListNode(i)
cur = cur.next
return ping.next
标签:II,head,right,ListNode,que1,next,链表,CodingPark,left 来源: https://blog.csdn.net/weixin_38411989/article/details/117594200