We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
this part of code essentially means, the next element to head 1(element 4) would be the result of the comparison between 4 and next head2's element which is 2.
now the result of the comparison between 4 and 2 would be assigned next to 4.
so, if head1's element is the largest, that ll be the final result of final comparison in this part of the code. but it would fail in the case, where 4(head1) is compared to 10(head2), where it goes to the else part.
here head1's next element,i.e 5 is compared to current head2 i.e 10, again first part of code(comparison if clause) is executed, where it again fails coz 10>5. then 10 is compared to 6, and again 10>6. so head1 is returned, which is 6,with the head2 s elemnt i.e 10. and if you observe closely , this comparison was assigned to head1(6)'s next.
now this 10 will bubble up to the previous part where it becomes 6->10. now this link moves up and becomes 5->6->10, which moves up to be 4->5->6->10, again 2->4->5->6->10 and finally becomes 1->2->4->5->6->10.
Merge two sorted linked lists
You are viewing a single comment's thread. Return to all comments →
consider head1: 4 ->5 ->6 and head2: 1 ->2 ->10 i am sure you might have understood if head1 is null then return head2, and vice versa now with.
if(head1.data>=head2.data) { head2.next=mergeList(head1,head2.next); return head2; }
so, if head1's element is the largest, that ll be the final result of final comparison in this part of the code. but it would fail in the case, where 4(head1) is compared to 10(head2), where it goes to the else part.
here head1's next element,i.e 5 is compared to current head2 i.e 10, again first part of code(comparison if clause) is executed, where it again fails coz 10>5. then 10 is compared to 6, and again 10>6. so head1 is returned, which is 6,with the head2 s elemnt i.e 10. and if you observe closely , this comparison was assigned to head1(6)'s next.
now this 10 will bubble up to the previous part where it becomes 6->10. now this link moves up and becomes 5->6->10, which moves up to be 4->5->6->10, again 2->4->5->6->10 and finally becomes 1->2->4->5->6->10.
hope it helped understand recursion.