題目描述
將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
示例:
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
思路
使用2個指針分別遍歷每個鏈表,向後移動val值較小的指針。當某一個指針爲null
後,直接讓鏈表指向另一個指針即可。
代碼
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {return l2;}
if (l2 == null) {return l1;}
ListNode head = new ListNode(0);
ListNode tail = head;
while (l1 != null && l2 != null) {
if (l1.val <= l2.val) {
tail.next = l1;
l1 = l1.next;
} else {
tail.next = l2;
l2 = l2.next;
}
tail = tail.next;
}
tail.next = l1 == null ? l2 : l1;
// 由於head處是自定義的new ListNode(0),所以此時返回head.next
return head.next;
}