My solution using python


  • 0
    L
    def reverseBetween(self, head, m, n):
        """
        :type head: ListNode
        :type m: int
        :type n: int
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        # add a node to avoid reverse head
        dummy = ListNode(0)
        dummy.next = head
        pre = dummy
        for i in range(m - 1):
            pre = pre.next
        p = pre.next
        # pre is the pre node of reverselist
        # p always point the last node in the reverselist
        for i in range(n - m):
            tmp = pre.next
            pre.next = p.next.next
            p.next = p.next.next
            pre.next.next = tmp
        # return the next node of dummy
        return dummy.next

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.