Skip to content
BytePatterns

Reverse Nodes in Groups of K

HardLinked Lists#in-place-reversal#dummy-head~35m

Problem

A packet buffer is stored as a singly linked list, and the transmitter needs the packets reversed in blocks of k. Given the head of the list and an integer k ≥ 1, reverse the nodes of each consecutive block of k and return the new head. If fewer than k nodes remain at the end, leave them in their original order. Rewire the next pointers rather than copying values, and use only O(1) extra space. The list has up to 5,000 nodes.

Examples

Input:  list = 1 -> 2 -> 3 -> 4 -> 5, k = 2
Output: 2 -> 1 -> 4 -> 3 -> 5
Why:    5 is a block of one, shorter than k, so it stays put
Input:  list = 1 -> 2 -> 3 -> 4 -> 5, k = 3
Output: 3 -> 2 -> 1 -> 4 -> 5
Input:  list = 1 -> 2, k = 1
Output: 1 -> 2
Why:    edge case, blocks of one never change

Hints

0 / 3

Stuck on the idea rather than the code? Reverse a Linked List covers it.