Problem
Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.
Algorithm
Use a list save the data and reverse the sublist.
Code
# 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, m: int, n: int) -> ListNode:
if m >= n or not head:
return head
data = [0] * (n-m+1)
p = head
for i in range(m-1):
p = p.next
q = p
for i in range(m, n+1):
data[n-i] = q.val
q = q.next
q = p
for i in range(m, n+1):
q.val = data[i-m]
q = q.next
return head