/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
//特殊值处理
if(list1==null && list2==null){
return null;
}
//链表1为空
if(list1 == null){
return list2;
}
//链表2为空
if(list2 == null){
return list1;
}
//链表1,2都不为空
//与合并两个有序的数组步骤一样
ListNode list = null;
ListNode temp = null;
//初始化新链表的头指针
if(list1.val < list2.val){
list = list1;
list1 = list1.next;
}else{
list = list2;
list2 = list2.next;
}
temp = list;
while(list1!=null && list2!=null){//两个链表都不为空时,
if(list1.val < list2.val){
temp.next = list1;
list1 = list1.next;
}else{
temp.next = list2;
list2 = list2.next;
}
temp = temp.next;
}
if(list1 == null){//链表1已经被合并
temp.next = list2;
}
if(list2 == null){//链表2已经被合并
temp.next = list1;
}
return list;
}
}