DAY 29
0

## [Day29] 30 天挑戰演算法 - 合併兩個已排序的 List

L1 = {1, 2, 4, 7, 8}
L2 = {5}

1. L1, L2 都為 Null 時
2. L1 為 Null 時
3. L2 為 Null 時

``````public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null)
return null;
else if (l1 != null && l2 == null)
return l1;
else if (l1 == null && l2 != null)
return l2;
...(略)
}
``````

``````...(略)
ListNode head = null;
if (l1.val < l2.val){
head = new ListNode(l1.val);
l1 = l1.next;
} else{
head = new ListNode(l2.val);
l2 = l2.next;
}
...(略)
``````

``````...(略)

ListNode node = head;
while(l1 != null || l2 != null) {
// l1, l2 都不是 null, 並且 l1 較小
if (l1 != null && l2 != null && l1.val < l2.val) {
node.next = new ListNode(l1.val);
l1 = l1.next;
// l1, l2 都不是 null, 並且 l2 較小
} else if (l1 != null && l2 != null && l1.val > l2.val ) {
node.next = new ListNode(l2.val);
l2 = l2.next;
// l2 不是 null ( l1 為 null)
} else if (l2 != null) {
node.next = new ListNode(l2.val);
l2 = l2.next;
// l1 不為 null (l2 是 null)
} else if (l1 != null) {
node.next = new ListNode(l1.val);
l1 = l1.next;
}
node = node.next;
}

return head;
``````

``````node.next = new ListNode(l1.val);
l1 = l1.next;
``````

``````node.next = new ListNode(l2.val);
l2 = l2.next;
``````

1. L2 已經沒有節點了(也就是等於 Null)
2. L2 的值大於 L1

``````if ( l2 == null || l1 != null && l2.val > l1.val) {
node.next = new ListNode(l1.val);
l1 = l1.next;
} else {
node.next = new ListNode(l2.val);
l2 = l2.next;
}
node = node.next;
``````