Given the head of a linked list, reverse every k nodes as a group. If remaining nodes < k, leave them as-is.

Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Explanation: Groups of 2: [1,2]→[2,1], [3,4]→[4,3], [5] stays.
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]

Count k nodes; if fewer remain, stop. Reverse the group of k, then recurse on the rest.

public ListNode reverseKGroup(ListNode head, int k) { ListNode curr = head; int count = 0; while (curr != null && count < k) { curr = curr.next; count++; } if (count < k) return head; ListNode prev = null, node = head; for (int i = 0; i < k; i++) { ListNode next = node.next; node.next = prev; prev = node; node = next; } head.next = reverseKGroup(node, k); return prev; }
Complexity Analysis:

Time complexity: O(n)
Space complexity: O(n/k) — recursion stack depth