← 返回 bytedance 的题目列表Reverse Nodes in k-Group (reverse even if last group size < k)
类型:online_judge
Given the head of a singly linked list head and an integer k, reverse the list in groups of k nodes and return the new head.
Different from the standard version: if the last group has fewer than k nodes, you must still reverse that remaining group.
You need to define ListNode yourself (with val and next).
Input Format
Line 1: integer k
Line 2: integer n (length of the list)
Line 3: n integers as node values in order
Output Format
Print the node values of the resulting list, space-separated.
Constraints
1 <= n <= 2 * 10^5
1 <= k <= 2 * 10^5
Node values fit in 32-bit signed integer
Examples
Example 1:
2
5
1 2 3 4 5
Output:
2 1 4 3 5
Example 2 (reverse the last short group too):
3
5
1 2 3 4 5
Output:
3 2 1 5 4
Example
Input
2
5
1 2 3 4 5
Output
2 1 4 3 5