public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
// 新开存储空间或者不开存储空间
if(list1 == null) return list2;
if(list2 == null) return list1; // 边界情况判断
ListNode head = list1;
ListNode fin1 = list1.next, fin2 = list2.next;
while(fin1 != null && list2 != null){
// 把list1设置为主链表,把list2加入list1中
if(list1.val <= list2.val && fin1.val >= list2.val){
list1.next = list2;
list2.next = fin1;
list1 = list1.next;
list2 = fin2;
if(fin2 != null) fin2 = fin2.next; // 准备要跳出循环
}else { // 如果不能加入则list1继续下后寻找可以加入的位置
list1 = fin1;
fin1 = fin1.next;
}
}
while(list1.next != null){ // 找到list1中最后一个元素
list1=list1.next;
}
list1.next = list2; // list1最后链接到list2
return head;
}
}