10-line recursive python solution 69ms

  • 1

    The idea is to keep 2 variables:
    new_head: current node that is moved to head
    tail: node after current node; might be null
    The first for loop checks if the list has enough nodes to reverse. The second loop reverse k nodes.

    def reverseKGroup(self, head, k):
        dummy = head
        for _ in range(k):
            if not dummy:
                return head
            dummy = dummy.next
        new_head, tail = head, head.next
        for _ in range(k-1):
            tail.next, tail, new_head = new_head, tail.next, tail
        head.next = self.reverseKGroup(tail, k)
        return new_head

Log in to reply

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