Reverse a Linked List in Groups of K
viaLeetCode
Problem: Given the head of a linked list and an integer k, reverse the nodes in groups of k and return the modified list. If the number of remaining nodes is less than k, leave them as-is (or reverse them too, per the variant asked).
Constraints: 1 <= k <= list length.
Example: [1,2,3,4,5], k=2 -> [2,1,4,3,5].
Approach: Iteratively (or recursively) reverse each group of k nodes: first check there are at least k nodes remaining, reverse that sub-list in place using the standard 3-pointer technique, reconnect it to the previously reversed portion and recurse/iterate on the remainder. O(n) time, O(1) space iteratively (O(n/k) stack depth recursively).
asked …