Title Description input Two monotonically increment list, output two list of linked lists, of course, we need to synthesize the list to meet the monotone non-reduction rule solution 1: non-recursive solution
1 classSolution {2 Public:3listnode* Merge (listnode* pHead1, listnode*pHead2)4 {5 if(!phead1 &&!phead2)returnNULL;6 if(PHead1 &&!phead2)returnPHead1;7 if(!phead1 && pHead2)returnpHead2;8ListNode *Newhead;9 if(Phead1->val < phead2->val)Ten { OneNewhead=PHead1; APhead1=phead1->Next; -}Else{ -Newhead=pHead2; thePhead2=phead2->Next; - } -ListNode *tmp=Newhead; - while(PHead1 &&pHead2) + { - if(Phead1->val < phead2->val) + { Atmp->next=PHead1; atTmp=tmp->Next; -Phead1=phead1->Next; -}Else{ -tmp->next=pHead2; -Tmp=tmp->Next; -Phead2=phead2->Next; in } - } to if(PHEAD1) tmp->next=PHead1; + if(pHead2) tmp->next=pHead2; - returnNewhead; the } *};
Solution 2: Recursive solution
1 classSolution {2 Public:3listnode* Merge (listnode* pHead1, listnode*pHead2)4 {5 if(Phead1==null)returnpHead2;6 if(Phead2==null)returnPHead1;7ListNode *Newhead;8 if(Phead1->val < phead2->val)9 {TenNewhead=PHead1; OneNewhead->next=merge (phead1->Next, pHead2); A}Else{ -Newhead=pHead2; -Newhead->next=merge (PHead1, phead2->next); the } - returnNewhead; - } -};
Merge two sorted lists