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.
simple c# code with comments to help you parse it;
{//this seems simple, if the lists are sorted, all you need to do is compare each head and insert//the smallest one into the new list;//the trickiest part of this would be proper node pointer management//we need a link to the head of the sorted list and a iterator pointer//to make sure we don't lose our place.SinglyLinkedListNodesorted=newSinglyLinkedListNode(0);SinglyLinkedListNodeind=newSinglyLinkedListNode(0);//point the sorted list to the first element in the listif(head1.data<=head2.data){sorted=head1;//point start of list at itind=head1;//point iterator at ithead1=head1.next;//move head1 pointer over 1}else{sorted=head2;// point start of list at itind=head2;// point iterator at it head2=head2.next;//move head2 pointer over 1}while(head1!=null||head2!=null){if(head1==null&&head2!=null){//continue down head2ind.next=head2;ind=ind.next;head2=head2.next;//make sure to move head2 over }elseif(head1!=null&&head2==null){//head2 is null and we can continue down head1ind.next=head1;ind=ind.next;head1=head1.next;// make sure to move head1 over}elseif(head1.data<=head2.data&&ind.next==head1){//head1 is the next lowest number and i next is pointing to it//so we just need to move head1 over 1 as well as i over on same list;head1=head1.next;ind=ind.next;}elseif(head1.data<=head2.data&&ind.next==head2){//head1 is the next lowest number and i next is not pointing to it//we need to make i next point to head1 then move head1 and iterator overind.next=head1;head1=head1.next;ind=ind.next;}elseif(head1.data>head2.data&&ind.next==head1){//head2 is the next lowest data and i next is not pointing to it//make i next point to head2 and move head2 and iterator overind.next=head2;head2=head2.next;ind=ind.next;}else{//head2 is next lowest dat and i next is pointing to it//move head2 and iterator overhead2=head2.next;ind=ind.next;}}returnsorted;}
Merge two sorted linked lists
You are viewing a single comment's thread. Return to all comments →
simple c# code with comments to help you parse it;