38. Reverse LL in group of given size K

Given the head of a singly linked list containing integers, reverse the nodes of the list in groups of k and return the head of the modified list. If the number of nodes is not a multiple of k, then the remaining nodes at the end should be kept as is and not reversed.

Do not change the values of the nodes, only change the links between nodes.

Example 1:

Input: head -> 1 -> 2 -> 3 -> 4 -> 5, k = 2

Output: head -> 2 -> 1 -> 4 -> 3 -> 5

Explanation: The groups 1 -> 2 and 3 -> 4 were reversed as 2 -> 1 and 4 -> 3.

Example 2:

Input: head -> 1 -> 2 -> 3 -> 4 -> 5, k = 3

Output: head -> 3 -> 2 -> 1 -> 4 -> 5

Explanation: The groups 1 -> 2 -> 3 were reversed as 3 -> 2 -> 1.

Note that 4 -> 5 was not reversed.

Now Your Turn!

Pick the correct output for the given input

Input: head -> 6 -> 1 -> 2 -> 3 -> 4 -> 7, k = 4

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= k <= number of nodes in the linked list <= 105
  • -104 <= ListNode.val <= 104

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/*
Definition of singly linked list:
struct ListNode
{
int val;
ListNode *next;
ListNode()
{
val = 0;
next = NULL;
}
ListNode(int data1)
{
val = data1;
next = NULL;
}
ListNode(int data1, ListNode *next1)
{
val = data1;
next = next1;
}
};
*/
 
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
 
}
};
Test Case

Input:

K
Nums