Title: 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.
Ideas: The topic is relatively simple, there are two ideas, one is to traverse the public length of two linked lists, by the size of the value of the various nodes connected, and finally the longer list of the remainder to append to the last. The second idea, which is similar to a natural merge sort, can be solved by using the idea of recursive separation, and it makes it easy for you to break the problem down into sub-problems.
Implementation code
Non-recursive:
/*Public class ListNode {int val; ListNode next = null; ListNode (int val) {this.val = val; }}*/ Public classSolution { PublicListNode Merge (listnode list1,listnode list2) {if(List1 = =NULL) returnList2; if(List2 = =NULL) returnList1; ListNode Head; if(list1.val<=list2.val) {head=List1; List1=List1.next; } Else{Head=List2; List2=List2.next; } ListNode Pnode=Head; while(List1! =NULL&& List2! =NULL) { if(List1.val <=list2.val) {Pnode.next=List1; List1=List1.next; } Else{Pnode.next=List2; List2=List2.next; } Pnode=Pnode.next; } while(List1! =NULL) {Pnode.next=List1; Pnode=Pnode.next; List1=List1.next; } while(List2! =NULL) {Pnode.next=List2; Pnode=Pnode.next; List2=List2.next; } returnHead; }}
Recursion:
/*Public class ListNode {int val; ListNode next = null; ListNode (int val) {this.val = val; }}*/ Public classSolution { PublicListNode Merge (listnode list1,listnode list2) {if(List1 = =NULL) returnList2; if(List2 = =NULL) returnList1; ListNode Head; if(List1.val <list2.val) {head=List1; Head.next=Merge (List1.next, List2); } Else{Head=List2; Head.next=Merge (List1, List2.next); } returnHead; }}
Merge two sorted lists