题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @param m int整型
# @param n int整型
# @return ListNode类
#
class Solution:
def reverseBetween(self , head: ListNode, m: int, n: int) -> ListNode:
# 当只反转一个时,就不需要任何操作了
if m == n:
return head
# 遍历链表
a = []
while head != None:
a.append(head.val)
head = head.next
# 获取反转后的值排列,这步是关键
a = a[:m-1]+a[m-1:n][::-1]+a[n:]
# 创建新的链表
newL = ListNode(a[0])
res = newL
for j in a[1:]:
newL.next = ListNode(j)
newL = newL.next
# 记得添加这个
newL.next = None
return res
查看11道真题和解析
SHEIN希音公司福利 363人发布