Unable to solve

please tell algo unable to solve after hint

Algorithm :

  • 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 . for reversing a linked list.
  • 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 )

function

Node *reverse (Node *head, int k)  
{  
    Node* current = head;  
    Node* next = NULL;  
    Node* prev = NULL;  
    int count = 0;  
      
    /*reverse first k nodes of the linked list */
    while (current != NULL && count < k)  
    {  
        next = current->next;  
        current->next = prev;  
        prev = current;  
        current = next;  
        count++;  
    }  
      
    /* next is now a pointer to (k+1)th node  
    Recursively call for the list starting from current.  
    And make rest of the list as next of first node */
    if (next != NULL)  
    head->next = reverse(next, k);  
  
    /* prev is new head of the input list */
    return prev;  
}  

i hope this helps
if yes hit a like and don’t forgot to mark doubt as resolved :grinning:
if you have more doubts regarding this feel free to ask

1 Like

what is the base case

this is controlled recursive call so no need for base case

first we are checking if(next!=NULL) and then call

you can make a base case
if(head==NULL) return NULL;

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.