Title to merge two sorted list sixteenth offer to prove safety

Two monotonically increasing input list and output list after synthesis of two lists, of course, after that we need to meet synthesis list - decreasing the rules.

Personal ideas: two pointers are recorded with two lists, each node corresponding to the comparison pointer size smaller chain scission, when there is a list the list is empty then the other can be received later.

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode Merge(ListNode list1,ListNode list2) {
12         if(list1==null)
13             return list2;
14         else if(list2==null)
15             return list1;
16         else{
17             ListNode temp = null;
18             if(list1.val<list2.val){
19                 temp = list1;
20                 list1 = list1.next;
21                 }else{
22                 temp = list2;
23                 list2 = list2.next;
24             }
25             ListNode r = temp;
26             while(list1!=null&&list2!=null){
27                 if(list1.val<list2.val){
28                     temp.next = list1;
29                     list1 = list1.next;
30                     temp = temp.next;
31                 }else{
32                     temp.next = list2;
33                     list2 = list2.next;
34                     temp = temp.next;
35                 }
36             }
37             if(list1==null){
38                 temp.next = list2;
39             }else{
40                 temp.next = list1;
41             }
42             return r;
43         }
44         
45     }
46 }

Guess you like

Origin www.cnblogs.com/haq123/p/12154810.html