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