Title: Merging two sorted lists
Title Description: Input two monotonically increasing list, output two linked list of the linked list, of course, we need to synthesize the linked list to meet the monotone non-reduction rules.
The idea that the problem is not difficult to feel, that is, under the discussion of the situation, there are two ways of circulation recursion
1 Public classSolution {2 PublicListNode Merge (listnode list1,listnode list2) {3 if(list1==NULL&&list2==NULL)return NULL;4 if(list1==NULL)returnList2;5 if(list2==NULL)returnList1;6ListNode head=NewListNode (0);7head.next=NULL;8ListNode root=head;9 while(list1!=NULL&&list2!=NULL){Ten if(list1.val<=list2.val) { Onehead.next=List1; AHead=head.next;; -list1=List1.next; - the } - Else if(list2.val<list1.val) { -head.next=List2; -Head=Head.next; +List2=List2.next; - + } A } at - if(list1!=NULL) head.next=List1; - if(list2!=NULL) head.next=List2; - returnRoot.next; - } -}
One more recursive.
1 Public classSolution {2 PublicListNode Merge (listnode list1,listnode list2) {3 if(list1==NULL)returnList2;4 if(list2==NULL)returnList1;5 if(list1.val<=list2.val) {6list1.next=Merge (list1.next,list2);7 returnList1;8 }9 if(list2.val<list1.val) {Tenlist2.next=Merge (list1,list2.next); One returnList2; A } - return NULL; - } the}
Sword finger offer-combined with two sorted lists