"Sword refers to the offer surface question 17" merge two sorted list

Source: Internet
Author: User

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

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.