<jupyter_start><jupyter_text>说明：    将链接列表从位置m反向到n。一次性完成。Note:     1 ≤ m ≤ n ≤ length of list.Example:    Input: 1->2->3->4->5->NULL, m = 2, n = 4    Output: 1->4->3->2->5->NULL<jupyter_code>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:
            return head
        root = ListNode(0)
        root.next = head
        pre = root
        
        # 在m之前，都是正序
        for i in range(m - 1):
            pre = pre.next
        
        # m之后，n之前，反序
        reverse = None
        cur = pre.next
        for i in range(n-m+1):
            next = cur.next
            cur.next = reverse
            reverse = cur
            cur = next
        
        pre.next.next = cur
        pre.next = reverse
        return root.next
        
#  比较笨重
class Solution:
    def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
        #  是位置不是值
        if m > n:
            m, n = n, m
        res = root = ListNode(0)
        self.vals = []
        self.helper(head)
        re_vals = self.vals[m-1:n][::-1]
        index = 1
        re_index = 0
        while index <= len(self.vals):
            if m <= index <= n:
                res.next = ListNode(re_vals[re_index])
                re_index += 1
            else:
                res.next = ListNode(self.vals[index-1])
            res = res.next
            index += 1
        return root.next
    
    def helper(self, root):
        if root:
            self.vals.append(root.val)
            self.helper(root.next)
        else:
            return<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11689070718877849, 'fraction_numerical': 0.014611338398597311, 'mean_word_length': 1.3484224965706446, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '275302', 'license': 'Apache-2.0', 'n_tokens_mistral': 596, 'n_tokens_neox': 583, 'n_words': 141, 'path': 'Linked List/0901/92. Reverse Linked List II.ipynb', 'repo_name': 'YuHe0108/Leetcode', 'size': '1711'}