codejump
HardPro challengePythonJavaScriptTypeScript

Linked List — Reverse Nodes in k-Group

Data StructuresLinked ListRecursion

solve(values, k) builds a singly linked list and reverses its nodes `k` at a time,
returning the resulting values. If fewer than k nodes remain at the end, that last
group stays as it is. You may only change links, not values, and the extra space must
be O(1).

For each group: check that k nodes really exist (walk k steps), reverse exactly those
k nodes while pointing the first one at whatever follows the group, then hook the
reversed group to the node that preceded it. A dummy head keeps the first group simple.

Examples

solve([1,2,3,4,5], 2)  → [2,1,4,3,5]
solve([1,2,3,4,5], 3)  → [3,2,1,4,5]
solve([1,2,3], 5)      → [1,2,3]       // not enough nodes for even one group

Sample tests

Test #1k = 2 with a leftover
Input: [[1,2,3,4,5],2]
Output: [2,1,4,3,5]
Test #2k = 3 with a leftover
Input: [[1,2,3,4,5],3]
Output: [3,2,1,4,5]
Test #3k larger than the list
Input: [[1,2,3],5]
Output: [1,2,3]