24. Reverse Nodes in k-Group

HardLinked List

Given the head of a linked list, reverse the nodes of the list `k` at a time and return the modified list. If the number of remaining nodes is less than `k`, leave them as-is. For example, given [1,2,3,4,5] and k = 2, reverse each pair: [2,1,4,3,5]. For k = 3, reverse the first group of 3 and leave the last 2: [3,2,1,4,5]. You may not alter the values in the nodes, only the nodes themselves may be changed.

Examples

Input: [1,2,3,4,5] 2

Output: [2,1,4,3,5]

Explanation: Reverse every pair: [1,2]->[2,1], [3,4]->[4,3], [5] remains. Result: [2,1,4,3,5].

Constraints

  • The number of nodes in the list is n
  • 1 <= k <= n <= 5000
  • 0 <= Node.val <= 1000
Loading...

Run checks all cases above. Submit evaluates all test cases.