Sword Point offer question 17-merge two sorted list

Source: Internet
Author: User

Topic:

Enter a list of two ascending orders, merge the two linked lists, and make the nodes in the new list continue to be sorted in ascending order.


Basic idea:

When we get the smaller head node in the two list and connect it to the linked list, the remaining nodes of the two list are still sorted, so the merging steps are the same as the previous one. This is the typical recursive process.

    #include <iostream> using namespace std;          typedef int ELEMTYPE;//Data type template typedef struct NODE//node {elemtype data;      struct Node *next;            }node;            typedef struct NODE * linklist;          Build table node* Creat_link (Node *head) {int x;                Node *p,*q;          Head= (node *) malloc (sizeof (node));                head->next=null;                Q=head;          cin>>x;               while (x!=999) {p= (node *) malloc (sizeof (node));              p->data=x;              p->next=null;              q->next=p;              Q=p;          cin>>x; Return head;//returns the header node after the table is completed}//////////output void Output_link (Node * head) {if (head==null) {cout<< "Empty list!"  <<endl;  Return  } Node *q;  q= head->next;  while (q!=null) {cout<<q->data<< "";  q=q->next;    } Cout<<endl;} Node * FOO (node *head1,node *head2) {if (head1==null) return Head2;else if (head2==null) return head1; Node * PRESULT=NULL;IF (Head1->data < Head2->data) {Presult=head1;presult->next=foo (head1->next,head2 );} Else{presult=head2;presult->next=foo (Head1,head2->next);}          return pResult;} void Main () {Node *head1=null;        Node *head2=null; Node * Phead1=creat_link (HEAD1);//Build Table Node * Phead2=creat_link (HEAD2); Output_link (pHead1);//Output Output_link (PHEAD2);    Node * result = foo (phead1,phead2); Output_link (Result->next);   }



Sword Point offer 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.