Sharing simple Python solution, beats 90%


  • 0
    class Solution(object):
        def reverseBetween(self, head, m, n):
            
            def reverse_list(head):
                if head is None:
                    return
                prev, cur = None, head
                while cur is not None:
                    next_ = cur.next
                    cur.next = prev
                    prev = cur
                    cur =  next_
            
            first, last, prev, i, j = head, head, head, n, m
            while last is not None and i > 1:
                last = last.next
                i -= 1
            while first is not None and j > 1:
                prev = first
                first = first.next
                j -= 1
            
            next_node = last.next
            
            if prev != first:
                prev.next = None
            last.next = None
            
            # Now reverse portion of the list
            
            reverse_list(first)
            
            # Attach with rest of list
            
            prev.next = last
            first.next = next_node
            if prev == head and m == 1:
                head = last
            return head

Log in to reply
 

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