Title: Input Two a list of ascending sorts, merging the two linked lists and making the nodes in the new list continue to be sorted in ascending order.
Idea: First, the definition of two head nodes are Head1 and Head2 linked list, and then compare the value of the first node, if Head1->mvalue is smaller than Head2->mvalue, then the head node, is Head1, recursive implementation of the following node sorting.
C + + code:
#include <iostream>using namespacestd;structlistnode{intM_nvalue; ListNode*M_pnext;}; ListNode* CreateList (intA[],intb) {ListNode* phead=null,*pnode=NULL; for(intI=0; i<b;i++) {ListNode* pnew=NewListNode (); Pnew->m_nvalue=A[i]; Pnew->m_pnext=NULL; if(phead==NULL) {Phead=pnew; Pnode=pnew; } Else{Pnode->m_pnext=pnew; Pnode=pnode->M_pnext; } } returnPhead;}voidPrintlist (listnode*phead) { if(phead==NULL) { return; } ListNode* pnode=Phead; while(pnode!=NULL) {cout<<pNode->m_nValue<<" "; Pnode=pnode->M_pnext; } cout<<Endl;} ListNode* Mergelink (listnode* head1,listnode*Head2) {ListNode* mergehead=NULL; if(head1==NULL)returnHead2; if(head2==NULL)returnHead1; if(head1==null&&head2==NULL)returnNULL; if(head1->m_nvalue>head2->m_nvalue) {Mergehead=Head2; Head2->m_pnext=mergelink (head2->m_pnext,head1); } Else{Mergehead=Head1; Head1->m_pnext=mergelink (head1->m_pnext,head2); } returnMergehead;}voidMain () {inta[]={3,4,5,6,8}; intb[]={1,2,7}; ListNode* Head1=createlist (A,5); ListNode* Head2=createlist (b,3); Printlist (HEAD1); Printlist (HEAD2); ListNode* head3=Mergelink (HEAD1,HEAD2); Printlist (HEAD3); }
Java code:
Public classMergelink { Public Static classListNode {intM_nvalue; ListNode M_pnext; }; Public StaticListNode CreateList (int[] A,intb) {ListNode phead=NULL, pnode=NULL; for(inti=0;i<b;i++) {ListNode pnew=NewListNode (); Pnew.m_nvalue=A[i]; Pnew.m_pnext=NULL; if(phead==NULL) {Phead=pnew; Pnode=pnew; } Else{Pnode.m_pnext=pnew; Pnode=Pnode.m_pnext; } } returnPhead; } Public Static voidprintlist (ListNode phead) {if(phead==NULL) { return; } ListNode Pnode=Phead; while(pnode!=NULL) {System.out.print (Pnode.m_nvalue+" "); Pnode=Pnode.m_pnext; } System.out.println (); } Public StaticListNode mergelink (listnode head1,listnode Head2) {ListNode mergehead=NULL; if(head1==NULL) returnHead2; if(head2==NULL) returnHead1; if(head1==NULL&&head2==NULL) return NULL; if(head1.m_nvalue>head2.m_nvalue) {Mergehead=Head2; Head2.m_pnext=Mergelink (HEAD2.M_PNEXT,HEAD1); } Else{Mergehead=Head1; Head1.m_pnext=Mergelink (HEAD1.M_PNEXT,HEAD2); } returnMergehead; } Public Static voidMain (string[] args) {inta[]={3,4,5,6,8}; intb[]={1,2,7}; ListNode Head1=createlist (a,5); ListNode Head2=createlist (b,3); Printlist (HEAD1); Printlist (HEAD2); ListNode Head3=Mergelink (HEAD1,HEAD2); Printlist (HEAD3); }}
Sword Finger offer-Chapter III High-quality code (combined with two sort lists)