將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是經過拼接給定的兩個鏈表的全部節點組成的。node
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.python
示例:bash
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
複製代碼
迭代和遞歸都能解題。無非是依次將兩個鏈表每一個節點的值對比,取出值較小的節點,添加到新鏈表末尾。而後繼續比較兩個鏈表,直到其中一個鏈表遍歷完成,此時另外一個鏈表剩餘全部節點直接添加到新鏈表以後便可。其邏輯爲:函數
原鏈表:1->2->4->null,1->3->4->5->6->null 依次對比節點值,取出各自頭節點:1 = 1 值相同取出一個節點 1,組成新鏈表:1 此時原鏈表:2->4->null,1->3->4->5->6->nullspa
對比頭節點值:2 > 1 取出 1 節點,添加到新鏈表末尾:1->1 此時原鏈表:2->4->null,3->4->5->6->nullcode
對比頭節點值:2 < 3 取出 2 節點,添加到新鏈表末尾:1->1->2 此時原鏈表:4->null,3->4->5->6->nullcdn
.......依次類推,直到其中一個原鏈表爲空時:遞歸
原鏈表:null,4->5->6->null 新鏈表:1->1->2->3->4 這時其中一個原鏈表已經爲空,則直接將另外一個原鏈表添加到新鏈表末尾便可: 1->1->2->3->4->4->5->6->nullci
迭代法須要注意:先判斷原鏈表是否爲空;對比原鏈表第一個節點值的大小,選擇較小一個做爲新鏈表的頭節點。以後才能按上述邏輯執行。get
若是添加一個虛擬節點做爲頭節點,則無需上述條件,但應當返回虛擬節點的下一個節點。
Java:
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(-1);//新建虛擬頭節點
ListNode cur = head;//當前節點指向虛擬頭節點
while (l1 != null && l2 != null) {//循環條件爲鏈表都不爲空
if (l1.val < l2.val) {//比較頭節點的值的大小
cur.next = l1;//當前節點鏈接到節點值較小的一個
l1 = l1.next;//刷新原鏈表頭節點
cur = cur.next;//刷新當前節點
} else {
cur.next = l2;
l2 = l2.next;
cur = cur.next;
}
}
if (l1 == null) cur.next = l2;//選擇另一個不爲空的原鏈表,鏈接到新鏈表末尾
else cur.next = l1;
return head.next;//返回虛擬頭節點的下一個節點,即真實頭節點
}
}
複製代碼
Python3:
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode(-1)
cur = head;
while l1 and l2:
if l1.val <= l2.val:
cur.next = l1
cur = cur.next
l1 = l1.next
else:
cur.next = l2
cur = cur.next
l2 = l2.next
if l1:
cur.next = l1
else:
cur.next = l2
return head.next
複製代碼
遞歸基線條件爲:原鏈表其中之一遇到空節點。返回值爲:另外一個鏈表剩餘部分的頭節點。
遞歸判斷頭節點的值的大小,取小的節點添加到新鏈表以後。將剩餘鏈表傳回遞歸函數。
Java:
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;//基線條件
if (l2 == null) return l1;//基線條件
ListNode head;
if (l1.val <= l2.val) {//選擇節點值較小的節點
head = l1;//刷新頭節點
head.next = mergeTwoLists(l1.next, l2);//剩餘鏈表做爲參數傳入遞歸函數
} else {
head = l2;
head.next = mergeTwoLists(l1, l2.next);
}
return head;
}
}
複製代碼
Python3:
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1: return l2
if not l2: return l1
if l1.val <= l2.val:
head = l1
head.next = self.mergeTwoLists(l1.next, l2)
else:
head = l2
head.next = self.mergeTwoLists(l1, l2.next)
return head
複製代碼
歡迎關注 微.信公.衆號:愛寫Bug