用栈来解决
# 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]:
root = ListNode(next = head)
cur = root
i = 1
stack = []
while i<left:
cur = cur.next
i += 1
node = cur
while i<=right:
cur = cur.next
stack.append(cur)
i += 1
cur = cur.next
while stack:
node.next = stack.pop()
node = node.next
node.next = cur
return root.next