Reverse Nodes in k-Group

Hard

Topics
Linked ListRecursion

Given the head of a linked list, reverse the nodes k at a time and return the modified list. Nodes left over (fewer than k) stay in their original order.

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

  • 1 <= number of nodes <= 5000
  • 0 <= Node.val <= 1000
  • 1 <= k <= number of nodes
Run ⌘' · Submit ⌘⏎