Reverse a Linked List in Groups of K

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 fewer than k nodes remain at the end, leave them as they are (or reverse them too, depending on the variant asked).

Input / Output

  • Input: head, the head of a singly linked list, and an integer k.
  • Output: the head of the list with each consecutive group of k nodes reversed in place.

Constraints

  • 1 <= k <= list length.
  • Nodes must be relinked, not have their values swapped — value swapping is usually explicitly disallowed.
  • Confirm the tail behaviour up front: leaving a short final group untouched and reversing it anyway are both common asks and produce different answers.
  • Target O(1) extra space with the iterative solution.

Example

  • [1,2,3,4,5], k=2 → [2,1,4,3,5]. The trailing 5 stands alone and is left as-is.
  • [1,2,3,4,5], k=3 → [3,2,1,4,5], where 4 and 5 are too few to form a group.
  • k=1 returns the list unchanged; k equal to the list length is a single full reversal.
asked …
LeaderboardSalaryAccount