[Sword means offer] 16. Merge two sorted lists

Source: Internet
Author: User

"Idea 1" recursion

1 /*2 struct ListNode {3 int val;4 struct ListNode *next;5 listnode (int x):6 val (x), Next (NULL) {7     }8 };*/9 classSolution {Ten  Public: Onelistnode* Merge (listnode* pHead1, listnode*pHead2) A     { -         if(PHead1 = =NULL) -             returnpHead2; the         Else if(PHead2 = =NULL) -             returnPHead1; -listnode* res =NULL; -         if(Phead1->val <= phead2->val) { +res =PHead1; -Res->next = Merge (phead1->Next, pHead2); +}Else{ Ares =pHead2; atRes->next = Merge (phead1,phead2->next); -         } -         returnRes; -     } -};

"Train of Thought 2" non-recursive, create a new list and save the head node, the original two linked list to be compared sequentially inserted into the new linked list, and finally will have the remaining linked list directly connected.

1 /*2 struct ListNode {3 int val;4 struct ListNode *next;5 listnode (int x):6 val (x), Next (NULL) {7     }8 };*/9 classSolution {Ten  Public: Onelistnode* Merge (listnode* pHead1, listnode*pHead2) { A         if(PHead1 = =NULL) -             returnpHead2; -         Else if(PHead2 = =NULL) the             returnPHead1; -listnode* res =NULL; -listnode* cur =NULL; -          while(PHead1! = NULL && pHead2! =NULL) { +             if(Phead1->val <= phead2->val) { -                 if(res = =NULL) +res = cur =PHead1; A                 Else{ atCur->next =PHead1; -Cur = cur->Next; -                 } -PHead1 = phead1->Next; -}Else{ -                 if(res = =NULL) inres = cur =pHead2; -                 Else{ toCur->next =pHead2; +Cur = cur->Next; -                 } thePHead2 = phead2->Next; *             } $         }Panax Notoginseng         if(PHead1 = =NULL) { -Cur->next =pHead2; the         } +         if(PHead2 = =NULL) { ACur->next =PHead1; the         } +         returnRes; -     } $};

[Sword means offer] 16. Merge two sorted lists

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.