Skip to main content

Reverse Nodes in k-Group

HardPremium

Given the head of a linked list and a positive integer k, reverse the nodes of the list k at a time and return the new head.

If the number of nodes isn't a multiple of k, leave the last group of fewer than k nodes in its original order. Change the links between nodes, not the values inside them.

Example 1

Input: head = [1, 2, 3, 4, 5], k = 2 Output: [2, 1, 4, 3, 5]

1, 2 and 3, 4 are reversed. 5 is a group of one, which is fewer than k, so it stays.

Example 2

Input: head = [1, 2, 3, 4, 5], k = 3 Output: [3, 2, 1, 4, 5]

Constraints

  • The list has n nodes, where 1 <= k <= n <= 5000.
  • 0 <= Node.val <= 1000