标签:ber nod dex null alt pac index ace 新建
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null && list2 == null) return null;
else{
ListNode list3 = new ListNode(0); //先创建一个表头,方便往后加
ListNode tem = list3;
while(list1 != null && list2 != null){
if(list1.val <= list2.val){
tem.next = list1; //应该是把后边的全接过来了,但在后续操作中会断开,数据不会丢失。(不用新建结点赋值)
list1 = list1.next;
tem = tem.next;
}
else {
tem.next = list2;
list2 = list2.next;
tem = tem.next;
}
}
if(list1 == null && list2 != null){//把剩余的加上去
tem.next = list2;
}
else if(list2 == null && list1 != null){
tem.next = list1;
}
return list3.next;
}
}
}
另 递归方法:
public
ListNode Merge(ListNode list1,ListNode list2) {
if
(list1 ==
null
){
return
list2;
}
if
(list2 ==
null
){
return
list1;
}
if
(list1.val <= list2.val){
list1.next = Merge(list1.next, list2);
return
list1;
}
else
{
list2.next = Merge(list1, list2.next);
return
list2;
}
}
标签:ber nod dex null alt pac index ace 新建
原文地址:https://www.cnblogs.com/dyq19/p/10472793.html