将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有结点组成
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
题目来源:力扣(LeetCode)
1.1使用循环和双指针,生成的链表时另外一条新链表。时间复杂度为O(m+n),空间复杂度为
O(1)
/*循环+双指针 */
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(list1 == null) return list2;
if(list2 == null) return list1;
ListNode resultNode = new ListNode(0);
ListNode p = resultNode;//设置结果结点
while(list1 != null && list2 != null){
if(list1.val < list2.val){
p.next = list1;//结果结点指向l1值
list1 = list1.next;//l1指向自身下一结点
}else{
p.next = list2;//结果结点指向l2值
list2 = list2.next;//l2指向自身下一结点
}
p = p.next;
}
if(list1 != null) //l2链表比较完了,l1还有数
p.next = list1;
if(list2 != null)//l1链表比较完了,l2还有数
p.next = list2;
return resultNode.next;
}
}
1.2使用递归,时间复杂度为O(m+n),空间复杂度为O(m+n)
if(list1 == null) return list2;//边界条件检查
if(list2 == null) return list1;
if(list1.val < list2.val){
list1.next = mergeTwoLists(list1.next,list2);//递归调用自身
return list1;
}
list2.next = mergeTwoLists(list1,list2.next);
return list2;
}