Skip to content

Reverse Nodes in k-Group

HardLinked List
Decode it first. Clues, constraints, pattern and plan before any code.

You get the head of a linked list and a number k. Reverse the nodes k at a time: the first k nodes flip, then the next k, and so on. If fewer than k nodes are left at the end, leave them as they are. Relink the nodes themselves rather than swapping values, and return the new head.

1 -> 2 -> 3 -> 4 -> 5, k = 2   →  2 -> 1 -> 4 -> 3 -> 5
1 -> 2 -> 3 -> 4 -> 5, k = 3   →  3 -> 2 -> 1 -> 4 -> 5
1 -> 2 -> 3 -> 4 -> 5, k = 1   →  1 -> 2 -> 3 -> 4 -> 5

Try to use only O(1) extra memory.

Constraints

  • 1 <= k <= number of nodes <= 5000
  • 0 <= Node.val <= 1000