← 返回 bytedance 的题目列表Reverse Linked List in Groups of K Including the Last Partial Group
类型:online_judge
Problem Description
Given the head of a singly linked list head and a positive integer k, split the linked list into consecutive groups of size k and reverse the nodes in each group.
Unlike LeetCode 25, if the final remaining group contains fewer than k nodes, you should still reverse that remaining group.
You should modify the linked list pointers in place. Do not copy node values into an array for processing.
Input Format
For online judging, the input is provided as:
n k
v1 v2 ... vn
n is the number of nodes in the linked list.
k is the group size.
v1 ... vn are the node values in list order: v1 -> v2 -> ... -> vn.
Output Format
Print the values of the modified linked list, separated by spaces.
Constraints
1 <= n <= 10^5
1 <= k
The original interview problem guarantees k <= n.
Node values are integers within the 32-bit signed integer range.
Expected time complexity: O(n).
Expected extra space complexity: O(1).
Example 1
Input:
5 2
1 2 3 4 5
Output:
2 1 4 3 5
Explanation: Reverse every 2 nodes. The final group [5] is also reversed, so it remains unchanged.
Example 2
Input:
5 3
1 2 3 4 5
Output:
3 2 1 5 4
Explanation: [1,2,3] becomes [3,2,1], and the final partial group [4,5] is also reversed to [5,4].
Example
Input
5 2
1 2 3 4 5
Output
2 1 4 3 5