92. 反转链表 II

思路:将中间的链表进行反转,然后前后进行连接,需要注意有前结点和没有前结点的情况。

class Solution(object):
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """

        pre = dummy = ListNode(0)
        pre.next = head
        for i in range(m-1):
            pre = pre.next
            
        cur = pre.next
        tail = None
        for i in range(n-m+1):
            tmp = cur.next
            cur.next = tail
            tail = cur
            cur = tmp
        
        # 实现反转链表和双边结点的互相连接
        # cur当前是反转链表块的下一个结点,因此将反转链表的末尾结点指向该结点
        pre.next.next = cur
        # tail则为反转链表中的头结点,因此将反转链表的前一个结点指向反转链表的头结点
        pre.next = tail
        
        return dummy.next