Not understanding the fuction

nodereverse(nodehead,int k)
{
node* current = head;
node* next = NULL;
node* prev = NULL;
int count = 0;

while (current != NULL && count < k)  
{  
    next = current->next;  
    current->next = prev;  
    prev = current;   
    current = next;  
    count++;  
}  

if (next != NULL)  
head->next = reverse(next, k);  

return prev;

}

can you please explain what this function is doing i am very confuses about this function,

what this function do is to to reverses the linked list into the group of size k,
for eg :-
Input : 1->2->3->4->5->6->7->8->NULL, K = 3
Output : 3->2->1->6->5->4->8->7->NULL

Input : 1->2->3->4->5->6->7->8->NULL, K = 5
Output : 5->4->3->2->1->8->7->6->NULL

Coming to its working ,

  • Reverse the first sub-list of size k. While reversing keep track of the next node and previous node. Let the pointer to the next node be next and pointer to the previous node be prev . (This requires the knowledge of linked list reversal , if you haven’t done that question than do it first than try this )
  • head->next = reverse(next, k) ( Recursively call for rest of the list and link the two sub-lists )
  • Return prev ( prev becomes the new head of the list (refer the diagram)

In case of any doubt feel free to ask :slight_smile:
Mark your doubt as resolved if you got the answer

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.