Given the head of a linked list, reverse the nodes of the 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 linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
You may not alter the values in the list's nodes, only nodes themselves may be changed.
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
n.1 <= k <= n <= 50000 <= Node.val <= 1000Follow-up: Can you solve the problem in O(1) extra memory space?
The most straightforward approach to reverse nodes in k-group involves using an additional data structure, such as a list or stack, to store the k nodes temporarily. Once we have stored k nodes, we reverse them and link them back to the list.
The recursive approach is an elegant way to solve the problem. In each recursive call, reverse a k-sized group and link the rest using recursion.
An optimal solution with an iterative approach avoids using extra space apart from the input list itself.