描述
输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
数据范围:0≤n≤1000,节点值 1000≤节点值≤1000 要求:空间复杂度?O(1),时间复杂度?O(n)
如输入{1,3,5},{2,4,6}时,合并后的链表为{1,2,3,4,5,6},所以对应的输出为{1,2,3,4,5,6}
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1==null){
return list2;
}
if(list2==null){
return list1;
}
ListNode result = new ListNode(-1);
ListNode guard = result;
while(true){
if(list1 == null && list2 == null){
break;
}
if(list1==null){
result.next = list2;
list2 = list2.next;
result = result.next;
}else if(list2 == null){
result.next = list1;
list1 = list1.next;
result = result.next;
}else if(list1.val<=list2.val){
result.next = list1;
list1 = list1.next;
result = result.next;
}else if(list1.val>list2.val){
result.next = list2;
list2 = list2.next;
result = result.next;
}
}
return guard.next;
}
递归:
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if(list1 == null)
return list2;
if(list2 == null)
return list1;
if(list2.val>=list1.val){
list1.next=Merge(list1.next,list2);
return list1;
}else{
list2.next=Merge(list1,list2.next);
return list2;
}
}
}
|