C + + single-linked list inversion, two sequential linked list merge still orderly

Source: Internet
Author: User

1#include <iostream>2 3 structNode4 {5     intdata;6Node *Next;7 };8 9typedefstructnode node;Ten  OneNode *reverse (node *head) A { -     if(NULL = = Head | | NULL = = head->next) -         returnhead; theNode *P1 =head; -Node *P2 = p1->Next; -Node *P3 = p2->Next; -P1->next =NULL; +      while(P3! =NULL) -     {    +P2->next =P1; AP1 =P2; atP2 =P3; -P3 = p3->Next; -     }    -  -P2->next =P1; -Head =P2; in     returnhead; - } to  + //Loop Algorithm -Node *merge (node *head1, node *head2) the { *     if(NULL = =head1) $         returnhead2;Panax Notoginseng     if(NULL = =head2) -         returnHead1; theNode *head =NULL; +Node *P1 =NULL; ANode *P2 =NULL; the     if(Head1->data < head2->data) +     { -Head =Head1; $P1 = head1->Next; $P2 =head2; -     } -     Else the     { -Head =head2;WuyiP2 = head2->Next; theP2 =Head1; -     } Wu  -Node *cur =head; About      while(Null!=p1 && null!=p2) $     { -         if(P1->data < p2->data) -         { -Cur->next =P1; ACur =P1; +P1 = p1->Next; the         } -         Else $         { theCur->next =P2; theCur =P2; theP2 = p2->Next; the         } -     } in     if(NULL = =p1) theCur->next =P2; the     if(NULL = =p2) AboutCur->next =P1; the  the     returnhead; the } +  - //Recursive algorithm theNode *mergerecursive (node *head1, node *head2)Bayi { the     if(NULL = =head1) the         returnhead2; -     if(NULL = =head2) -         returnHead1; theNode *head =NULL; the  the     if(Head1->data < head2->data) the     { -Head =Head1; theHead->next = Mergerecursive (head1->Next, head2); the     } the     Else94     { theHead =head2; theHead->next = Mergerecursive (Head1, head2->next); the     }98  About     returnhead; - }101 102 intMainvoid)103 {104     return 0; the}

C + + single-linked list inversion, two sequential linked list merge still orderly

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.