输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
非递归写法,新建链表储存结点,移动两个链表的指针。
这里需要用两个链表,内容相同,只是指针指向不同。
指向新链表头的负责输出,指向链表尾部的附加添加新结点。
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
//特殊情况
if (list1==null && list2==null) return null;
else if (list1==null) return list2;
else if (list2==null) return list1;
//一般情况
ListNode current = null;
ListNode result = null;
while(list1!=null && list2!=null){
if (list1.val <= list2.val){
if (result == null){ //如果用current是不行的,因为每次current都会指向next,一直在变可能就null了
current = result = list1;//指向同一个对象,确保输出结果一直是指向头
}else{
current.next = list1;
current = current.next;
}
list1 = list1.next;
}else {
if (result==null){
current = result = list2;
}else{
current.next = list2;
current = current.next;
}
list2 = list2.next;
}
}
if (list1 == null){
current.next = list2;
}
if (list2 == null){
current.next = list1;
}
return result;
}
}
递归写法:
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
//特殊情况
if (list1==null && list2==null) return null;
else if (list1==null) return list2;
else 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;
}
}
}
其中:current = result = list1; 等于
result = list1;
current = result;