LL - K Reverse Problem

code - https://ide.codingblocks.com/s/37504
Ques - https://hack.codingblocks.com/contests/c/511/116
I am not getting what i am doing wrong and so that’s why the recursion is not working properly.

void printk(node*head,int k){
int count=0;
node *temp = head;
while(count++ < k-1){
temp = temp->next;
}
reverse(temp,k);
}
in this function you are reversing the list from the kth element… you should send the first element as parameter in the reverse function so that it will reverse next k elements and then again you should call the reverse function for next k elements… modify your approach according to this

Code - https://ide.codingblocks.com/s/37603
@sanjeetboora Now also its showing some weird output … plzz correct my code.

I have corrected your code, you can refer this https://ide.codingblocks.com/s/37710

1 Like

Thanks, but actually your code completely changed my code and After Seeing your code I edited my code in this way … . and it worked too.
Take a look at it - https://ide.codingblocks.com/s/37870
It would be very helpfull if u can tell that why it worked now ? after changing only few lines.

In your earlier code

  • Print function was not correct as you were printing in the reverse order
  • In main() you were not updating the head node which was returned by reverse()
    so after correcting these… its working fine.

my only doubt is why have you retrun prev in the reverse function ?