Reverse Nodes in k-Group

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

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k, the remaining nodes at the end should stay in their original order.

You may not alter the values in the list's nodes; only the nodes themselves may be changed.

Example 1
[1] -> [2] -> [3] -> [4] -> [5] -> null
---
[2] -> [1] -> [4] -> [3] -> [5] -> null
Inputhead = [1,2,3,4,5], k = 2
Output[2,1,4,3,5]
The nodes are reversed in pairs: 1 and 2 become 2 and 1, and 3 and 4 become 4 and 3; node 5 remains as is.
Example 2
[1] -> [2] -> [3] -> [4] -> [5] -> null
---
[3] -> [2] -> [1] -> [4] -> [5] -> null
Inputhead = [1,2,3,4,5], k = 3
Output[3,2,1,4,5]
The first three nodes are reversed as one group, while the remaining two nodes stay in their original order.

Constraints

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

Asked at 27 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate