reverse linked list by k
//Iterative program in C++ to reverse a linked list in groups of k
// (just before end of 2nd iteration of outer loop) [ 1->2->3->4->5->NULL ]
// 1 <- 2 3 <- 4 5 ->NULL (k=2)
^ ^ ^
| | |
prev_tail temp_head walker
void reverse_by_k(Node **head,int k){
Node* temp_head = *head,*walker = *head,*prev_tail = NULL;
while(walker){
int i=0;
Node *temp = NULL,*prev = NULL;
//initialize temporary head to set previous tail later
temp_head = walker;
//reverse group of k nodes
while(i<k && walker){
temp = walker->next;
walker->next = prev;
prev = walker;
walker = temp;
i++;
}
if(prev_tail){
//previous tail has to point to temporary head of current group
prev_tail->next = prev;
prev_tail = temp_head;
} else{
prev_tail = *head;
*head = prev;
}
}
}