Easy-to-understand python solution

  • 0
    class Solution(object):
    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
        p = head
        beforeM = None
        for i in range(1,m):
            beforeM = p
            p = p.next
        atM = p # beforeM is the (m-1)th one in list before reverse, atM is the (m)th one.
        prev = p
        p = p.next
        for i in range(m+1, n+1): # reverse link from m to n
            tmp = p.next
            p.next = prev
            prev = p
            p = tmp
        atM.next = p # end of the sublist
        if beforeM:
            beforeM.next = prev
        else: # in case m == 1, i.e no one before m
            head = prev
        return head

Log in to reply

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