Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.You may not alter the values in the list’s nodes, only nodes themselves may be changed.
from leetcode_py import ListNodeclass Solution: # Time: O(n) # Space: O(1) def reverse_k_group(self, head: ListNode[int] | None, k: int) -> ListNode[int] | None: if not head or k == 1: return head # Check if we have at least k nodes curr: ListNode[int] | None = head count = 0 while curr and count < k: curr = curr.next count += 1 if count == k: # Reverse the first k nodes prev = self.reverse_k_group(curr, k) # Recursively reverse remaining groups curr = head while count > 0 and curr is not None: next_temp = curr.next curr.next = prev prev = curr curr = next_temp count -= 1 head = prev return head