Recursive Solution :
Node *reverseKGroup(Node *head, int k) {
// code here
// Recursive
struct Node* cur = head, *prev = NULL, *next = NULL;
int count = 0;
while(cur != NULL && count < k) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
count++;
}
if(next) head->next = reverseKGroup(next, k);
return prev;
}
Iterative Solution :
Node *reverseKGroup(Node *head, int k) {
// code here
// Iterative
struct Node* cur = head, *newHead = NULL, *tail=NULL;
while(cur) {
struct Node* cur1 = cur, *prev = NULL, *next = NULL;
int count = 0;
while(cur != NULL && count < k) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
count++;
}
if(newHead == NULL) newHead = prev;
if(tail) tail->next = prev;
tail = cur1;
}
return newHead;
}