想法:
當list為空離開迴圈
是: current.next = (list1==null ? list2:list1)
否:繼續執行null前的數值判斷
——>先判斷數值,再null
程式碼:
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode(0); //先生成最開始用來接到第一個node的dummy node
ListNode current = dummy; //current node用來做遍歷使用
while( list1 != null && list2 != null){
if (list1.val <= list2.val){
current.next = list1; //比較小的節點接到current的next上面
list1 = list1.next; //對應的list指標往下走
} else {
current.next = list2;
list2 = list2.next;
}
current = current.next; //current指標往下走
}
current.next = (list1==null ? list2:list1);
return dummy.next;
}
}
A == B ? A : B
(若真取A;假取B)
while( list1 != null && list2 != null)
——>當其中1個list為空立即離開,因此只先判斷null前的數值大小並排列當其1個list為空,用其判斷
current.next = (list1==null ? list2:list1)
——>可減少判斷時間,簡潔明瞭