Problem statement

https://binarysearch.com/problems/Reverse-Linked-List-Groups/

Solution

Equal to Leetcode 0025. Reverse Nodes in k-Group, but be careful about the last group, it is not said in problem description what we need to do with it.

Complexity

It is O(n) for time and O(1) for space.

Code

class Solution:
    def solve(self, head, k):
        dummy = LLNode(0)
        dummy.next = head
        cur, nxt, pre = dummy, dummy, dummy
        cnt = 0
        while cur.next:
            cnt += 1
            cur = cur.next
            
        while cnt > 0:
            cur = new = pre.next
            nxt = cur.next
            for _ in range(min(k, cnt) - 1):
                tmp = nxt.next
                nxt.next = cur
                cur = nxt
                nxt = tmp
            
            pre.next = cur
            new.next = nxt
            pre = new
            cnt -= k
            
        return dummy.next