Difficulty: Medium
Acceptance: %
Points: 30.00
Given a linked list, the task is to reverse the nodes in groups of size k (where k is provided as input). If the total number of nodes is not a multiple of k, the remaining nodes at the end should be treated as a smaller group and reversed as well.
Input: Linked List: 10 -> 20 -> 30 -> 40 -> 50, k = 2
Output: 20 -> 10 -> 40 -> 30 -> 50
Explanation: The first 2 elements 10, 20 are reversed to 20, 10. these are reversed first. The last element 50 remains as is since the group size is less than k.
Input: Linked List: 5 -> 15 -> 25 -> 35 -> 45, k = 1
Output: 5 -> 15 -> 25 -> 35 -> 45
Explanation: Since k = 1, each group has only one node, so no changes are made. Resultant linked list: 5 -> 15 -> 25 -> 35 -> 45.
Expected Time Complexity: O(n)
Expected Space Complexity: O(1)