While reversing the linked list in groups of size k, what operation does the following statement perform in reverse function:-
if(nex!=NULL)
hd->next=reverse(nex,rev)
return prev;
Reverse Function is:-
node* reverse(node * hd,int rev)
{
node * nex=NULL;
node * prev=NULL;
node * cur=hd;
int cnt=0;
while(cur!=NULL&&cnt<rev)
{
nex=cur->next;
cur->next=prev;
prev=cur;
cur=nex;
cnt++;
}
if(nex!=NULL)
hd->next=reverse(nex,rev)
return prev;
}
Problem in Linked List
see your aim is to reverse the linked list in size of K (rev here). So when you have reversed the first k nodes of linked list lets say ‘head1’. then you will reverse the remaining linked list in the same way and append it to the linked list ‘head1’.
So this statement is doing the same thing.
for ex:
L = 1->2->3->4->5->6 and K=2 then
head1 = 2->1 and remaining linked list is 3->4->5->6. so you will call the same reverse function with this modified linked list that will result 4->3->6->5 and then append it to head1 for final answer.
so your answer will be 2->1->4->3->6->5.
So this statement is doing this operation.