Merge Two Sorted Lists
1615 ワード
説明:
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.
分析:第1のチェーンテーブルが空の場合、第2のチェーンテーブル に戻る. 2 2 2番目のチェーンテーブルが空の場合は、1番目のチェーンテーブル(いずれも空の場合は空のチェーンテーブル) に戻る.第1のチェーンヘッダのノード値が第2のチェーンヘッダのノード値より小さい場合、第1のチェーンヘッダのノードは新しいチェーンヘッダのノードとし、後続のノードは連結l 1とする.nextおよびl 2の後のチェーンテーブル 第2のチェーンヘッダのノード値が第1のチェーンヘッダのノード値より小さい場合、第2のチェーンヘッダのノードは新しいチェーンヘッダのノードとし、後続のノードは連結l 2とする.nextおよびl 1の後のチェーンテーブル コード:
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.
分析:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) return l2;// l1 , l2
if(l2 == null) return l1;// l2 , l1
if(l1.val < l2.val) {//l1 l2 l1
l1.next = mergeTwoLists(l1.next, l2);// l1.next l2
return l1;
}
else {//l2 l1 l2
l2.next = mergeTwoLists(l1, l2.next);// l2.next l1
return l2;
}
}