Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a 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 list. If the number of nodes is not a multiple of k, leave the last nodes as is. Example: Input: head = [1,2,3,4,5], k = 3 Output: [3,2,1,4,5] Explanation: The first 3 nodes [1,2,3] are reversed. Pattern focus: In-Place Reversal (reverse in chunks).

Input Format

head = ListNode, k = int

Output Format

return ListNode

Constraints

  • The number of nodes is in the range [1, 10^4].
  • 1 <= k <= length of list

Examples

Example 1:

Input:

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

Output:

[3,2,1,4,5]

Explanation:

First 3 nodes reversed in-place.

Loading...
Reverse Nodes in k-Group - Linked List