K reverse LL- Segmentation Fault

https://ide.codingblocks.com/s/239962 please help me correct my code. What is the issue here I do not understand. Also please correct me, and do not send any other code. Thanks.

else{
ptr1->next=ptr2;
connect->next=p;
}
this is the error
see what in the second iteration of 9 3
1 2 3 4 5 6 7 8 9
ptr1 points to 6
connect points to 5
p points to 6
ptr2 is 7
so this makes 6’s next as 7
and 5’s next as 6 here reference to 4 is now lost
then after the for loop
ptr1 goes to NULL
and connect to 9
and in the next iteration when u access
ptr->next again that is the segmentation error
u need to dry run this once properly and you will understand how links works and not just like array
ur assumption here is that ptr1 will retain in the original way
but it also gets reversed
after the first iteration itself
before the final for loop
it becomes
3 2 1 4 5 6 so on
and here when ptr1 originally pointed to 1 it will still point to 1 and its next will now become 4


it is fixed here, now before submitting u need to check for the case when k is not a multiple of size which i would recommend for u to try on your own

1 Like

Hey thank you so much! I now understand it. Basically I was assuming ptr will stay at the first position whereas it will point to one only which is no more the first element and hence we do no need to put a loop. Also it was mentioned in the question that we need to assume that k is a factor of n.