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.
Method One: Recursion
Public classMergelist {/** * @paramargs*/ Public Static voidMain (string[] args) {//TODO auto-generated Method StubListNode List1 =NewListNode (); ListNode List2=NewListNode (); ListNode Second1=NewListNode (); ListNode Second2=NewListNode (); ListNode Third2=NewListNode (); List1.nextnode=Second1; List2.nextnode=Second2; Second2.nextnode=Third2; List1.data=1; Second1.data=3; List2.data=2; Second2.data=2; Third2.data=2; Mergelist P=Newmergelist (); System.out.println (P.merge2 (List1, List2)); } PublicListNode Merge (listnode list1,listnode list2) {ListNode list=NULL;//defines a list after completion, initialized to NULL, or it can be ListNode list=new listnode (); /** public class ListNode {int val; ListNode next = null; ListNode (int val) {this.val = val; }}*/ if(list1==NULL)returnList2; Else if(list2==NULL)returnList1; if(list1.data<list2.data) {List=List1; List.nextnode=Merge (LIST1.NEXTNODE,LIST2); } Else{List=List2; List.nextnode=Merge (LIST2.NEXTNODE,LIST1); } returnlist; }}
Method Two: Non-recursive
PublicListNode Merge2 (ListNode list1,listnode list2) {//a non-recursive approachListNode list=NULL;//Save the last synthesized list ListNode current=NULL;//Mobile Node if(list1==NULL)returnList2; Else if(list2==NULL)returnList1; while(list1!=NULL&& list2!=NULL){//and when it's not empty, you can compare it. if(list1.data<=list2.data) { if(list==NULL)//First determine whether the linked list is empty at the beginning, and assign the current value directly when empty=list=List1; Else{Current.nextnode=List1; Current=current.nextnode;//The current node moves backwards} List1=list1.nextnode;//The node of the comparison moves backwards}Else{ if(list==NULL) Current=list=List2; Else{Current.nextnode=List2; Current=Current.nextnode; } List2=List2.nextnode; } } if(list1==NULL) {//Finally, after the comparison is completed, determine whether the linked list reaches the end and insert the later part of the long list directly into the list Current.nextnode=List2; } if(list2==NULL) {Current.nextnode=List1; } returnlist; }
Linked list synthesis