Input two monotonically increasing list, output two list of linked lists, of course, we need to synthesize the linked list to meet the monotone non-reduction rules.
Idea: There can be two methods of implementation, the first is through the recursive implementation, the second is through non-recursive implementation.
Public classSolution { PublicListNode Merge (listnode list1,listnode list2) {if(List1 = =NULL&& List2 = =NULL){ return NULL; } if(List1 = =NULL&& list2!=NULL){ returnList2; } if(list1!=NULL&&list2==NULL){ returnList1; } listnode Merge=NULL; if(List1.val <list2.val) {Merge=List1; Merge.next=Merge (LIST1.NEXT,LIST2); }Else{Merge=List2; Merge.next=Merge (List1,list2.next); } returnmerge; }}
Non-recursive:
Public ListNode Merge (ListNode list1,listnode list2) {if (List1 = = NULL && List2 = = null) {retur n null; } if (List1 = = null && list2!=null) {return list2; } if (List1!=null&&list2==null) {return list1; } ListNode merge = null; ListNode merge2 = null; while (List1!=null &&list2!=null) {if (list1.val<list2.val) {if (merge = = null) { Merge2 = merge = List1; //Make sure the head node}else{merge.next = List1; Merge = Merge.next; } list1 = List1.next; }else{if (merge = = null) {merge2 = merge = List2; }else{merge.next = List2; Merge = Merge.next; This also wants to shift} LIST2 = List2.next; }} if (list1!=null) {merge.next = List1;//node assignment can} if (List2!=null) {Mer Ge.next = List2; } return merge2; }
Merge two sorted lists