题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
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)return list2; 13 if(list2 == null)return list1; 14 ListNode temp = null; 15 ListNode head = null; 16 if(list1.val > list2.val){ 17 temp =list2; 18 head =temp; 19 list2 = list2.next; 20 }else{ 21 temp =list1; 22 head =temp; 23 list1 = list1.next; 24 } 25 while(list1 != null && list2 != null) { 26 if(list1.val > list2.val){ 27 temp.next = list2; 28 temp=temp.next; 29 list2=list2.next; 30 }else{ 31 temp.next = list1; 32 temp=temp.next; 33 list1=list1.next; 34 } 35 } 36 if(list1 == null){ 37 temp.next = list2; 38 }else{ 39 temp.next = list1; 40 } 41 return head; 42 } 43 }