Short recursive python solution


  • 0
    M
        def reverseKGroup(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            def reverseInGroup(curr, k, length):
                #if remaining list is lesser than K, return as is without reversing this remaining group
                if length < k:
                    return curr
                    
                tail = curr
                count = 0
                prev = None
                
                while count < k and curr:
                    count += 1
                    temp = curr.next
                    curr.next = prev
                    prev = curr
                    curr = temp
                    
                groupHead = prev
                if curr: tail.next = reverseInGroup(curr, k, length-k)
                return groupHead
            
            if not head:
                return
            
            length, curr = 0, head
            while curr:
                length += 1
                curr = curr.next
            return reverseInGroup(head, k, length)```

Log in to reply
 

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