21. Merge Two Sorted Lists
原題目
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
翻譯
将兩個有序連結清單合并成一個新的連結清單。新的連結清單應該有由這兩個連結清單的頭部拼接而成。
解題思路
按照題意新連結清單有這兩個有序連結清單的頭部拼接而成,是以需要先找到比較兩個連結清單的頭部,
将較小的那個當做新連結清單的頭部,然後同時周遊兩個連結清單進行拼接就行了。
時間複雜度為:O(m+n)
空間複雜度為:O(0)
代碼示例-Java
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null ){
return l2;
}
if (l2 == null){
return l1;
}
ListNode ln;
ListNode head;
if (l1.val < l2.val){
head = ln = l1;
l1 = l1.next;
}else{
head = ln = l2;
l2 = l2.next;
}
while (l1 != null || l2 != null){
if (l1 == null){
ln.next = l2;
break;
}else if (l2 == null){
ln.next = l1;
break;
}
if (l1.val < l2.val){
ln.next = l1;
ln = ln.next;
l1 = l1.next;
}else{
ln.next = l2;
ln = ln.next;
l2 = l2.next;
}
}
return head;
}