# Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its 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.

Example:

Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

Note:

• Only constant extra memory is allowed.
• You may not alter the values in the list’s nodes, only nodes itself may be changed.

Solution:

Use recursion: (head is the current recursion node, cur is supposedly next)

1) if head == NULL, return

2) if depth == k, then prev->next is head, save head->next to next, found = true, save head to cur;

3) else do recursion: if(found) then cur->next = head.

4) if depth == 1: if(found) head->next is saved next, reset parameters, then do recursion; else return.

5) save head to cur

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void rK(ListNode* head, int depth, ListNode* prev, ListNode*& next, int k, bool &found, ListNode*& cur){
if(head == NULL){
return;
}
if(depth == k){
prev->next = head;
next = head->next;
found = true;
cur = head;
return;
}
rK(head->next, depth+1, prev, next, k, found, cur);
if(found){
cur->next = head;
}
if(depth==1){
if(found){
head->next = next;
next = NULL;
found = false;
cur = NULL;
rK(head->next, 1, head, next, k, found, cur);
}
else{
return;
}

}
cur = head;
return;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* next = NULL;
bool found = false;
ListNode* cur = NULL;
rK(head, 1, dummy, next, k, found, cur);
return dummy->next;
}
};


Remark:

#Easy reverse
end = last
while(head != last){
temp = head->next;
head->next = end;
end = head;
head = temp;
}