# 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.

/**
* 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){
return;
}
if(depth == k){
found = true;
return;
}
rK(head->next, depth+1, prev, next, k, found, cur);
if(found){
}
if(depth==1){
if(found){
next = NULL;
found = false;
cur = NULL;
}
else{
return;
}

}
return;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* dummy = new ListNode(0);
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