dsa · medium

Reverse Linked List in Groups of K

You are given the head of a singly linked list. Reverse nodes in groups of k. A leftover tail shorter than k stays in order. Return the new head.

Arguments

Walk .next on the ListNode. The judge prints the resulting values.

Example

[1,2,3,4,5], k=2[2,1,4,3,5]. k=3[3,2,1,4,5].

Reverse each full window of k nodes in place; leave a short tail.

Constraints

1 <= k <= length <= 500 Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.

Examples

Example 1

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

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

Example 2

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

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

Open in the Dojo editor