Simple Python with O(1) space


  • -1
    H
    class Solution(object):
        def reverseKGroup(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            if k<=1:
                return head
            t=head
            for _ in range(k):
                if t is None:
                    return head
                else:
                    t=t.next
                    
            slow= None
            midd= head
            fast= head.next
            midd.next=slow
            for _ in range(k-1):
                slow=midd
                midd=fast
                fast=fast.next
                midd.next=slow
            head.next=self.reverseKGroup(fast, k)
            return midd

Log in to reply
 

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