15-line simple python solution

  • 1
    class Solution(object):
        def reverseKGroup(self, head, k):
            res = ListNode(None)
            res.next = head
            a = list()        
            while head:
                head = head.next
                if len(a) == k:
                    res.next = a[k-1]
                    for i in range(k-1, 0, -1):
                        a[i].next = a[i-1]
                    a[0].next = self.reverseKGroup(head, k)
                    return res.next        
            return res.next

Log in to reply

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