Skip to content
CodeShare
All problems

Reverse Nodes in k-Group

Reverse a linked list k nodes at a time.

HardLinked list

Given the head of a linked list, reverse its nodes k at a time and return the new head. If the number of nodes isn't a multiple of k, the nodes left over at the end stay in their original order.

Change the links between nodes, not the values inside them. Lists are written as arrays in the examples.

Examples

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

Constraints

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