Ideas:
Compares the size of two linked list endpoint values in a recursive manner.
1#include <iostream>2 using namespacestd;3 4 structListNode5 {6 intVal;7ListNode *Next;8ListNode (intv =0): Val (v), next (NULL) {}9 };Ten OneListNode *sortedlistmerge (ListNode *phead1, ListNode *phead2) A { - if(Phead1 = =NULL) - returnphead2; the Else if(Phead2 = =NULL) - returnPhead1; - -ListNode *pmergedhead =NULL; + - if(Phead1->val < phead2->val) + { APmergedhead =Phead1; atPmergedhead->next = Sortedlistmerge (phead1->Next, phead2); - } - Else - { -Pmergedhead =phead2; -Pmergedhead->next = Sortedlistmerge (Phead1, phead2->next); in } - to returnPmergedhead; + } - the intMain () * { $ Panax NotoginsengListNode *L1 =NewListNode (1); -ListNode *H1 =L1; the for(inti =3; I <= One; i + =2) + { AListNode *temp =NewListNode (i); theL1->next =temp; +L1 = l1->Next; - } $ $ListNode *L2 =NewListNode (2); -ListNode *H2 =L2; - for(inti =4; I <= A; i + =2) the { -ListNode *temp =NewListNode (i);WuyiL2->next =temp; theL2 = l2->Next; - } Wu -cout<<"List1:"; AboutListNode *print1 =H1; $ while(Print1! =NULL) - { -cout<<print1->val<<" "; -Print1 = print1->Next; A } +cout<<Endl; the -cout<<"List2:"; $ListNode *print2 =H2; the while(Print2! =NULL) the { thecout<<print2->val<<" "; thePrint2 = print2->Next; - } incout<<Endl; the theListNode *mergelist =Sortedlistmerge (H1, H2); About thecout<<"Listmerge:"; theListNode *printlist =mergelist; the while(Printlist! =NULL) + { -cout<<printlist->val<<" "; thePrintlist = printlist->Next;Bayi } thecout<<Endl; the - -}
Test results:
List1:1 3 5 7 9 OneList2:2 4 6 8 Ten AListmerge:1 2 3 4 5 6 7 8 9 Ten One A
"Sword refers to the offer surface question 17" merge two sorted list