O(n) time and O(1) space python solution


  • 0
    M
        def reverseKGroup(self, head, k):
            if head is None or head.next is None:
                return head
            
            if k == 1:
                return head
            
            length = 0
            node = head
            while node:
                length += 1
                node = node.next
            
            reverseTimes = length // k
            
            dummy = ListNode(None)
            dummy.next = head
            prev = dummy
            start = head
            cur = head.next
            count = 1
            while cur and reverseTimes > 0:
                start.next = cur.next
                cur.next = prev.next
                prev.next = cur
                cur = start.next
                count += 1
                if count % k == 0 and cur:
                    prev = start
                    start = cur
                    cur = cur.next
                    count += 1
                    reverseTimes -= 1
            return dummy.next
    

Log in to reply
 

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