題目描述
輸入兩個單調遞增的鏈表,輸出兩個鏈表合成后的鏈表,當然我們需要合成后的鏈表滿足單調不減規則。
思路
若鏈表1的頭結點的值小于鏈表2的頭結點的值,則鏈表1的頭結點是合并后鏈表的頭結點。在剩余的結點中,鏈表2的頭結點的值小于鏈表1的頭結點的值,因此鏈表2的頭結點是剩余結點的頭結點,把這個結點和之前已經合并好的鏈表的尾結點鏈接起來。
Code
- Python
class Solution:
# 返回合并后列表
def Merge(self, pHead1, pHead2):
# write code here
if pHead1 is None:
return pHead2
if pHead2 is None:
return pHead1
if pHead1.val < pHead2.val:
pHead1.next = self.Merge(pHead1.next,pHead2)
return pHead1
else:
pHead2.next = self.Merge(pHead1,pHead2.next)
return pHead2
- JavaScript
/*function ListNode(x){
this.val = x;
this.next = null;
}*/
function Merge(pHead1, pHead2) {
if (pHead1 === null) return pHead2;
if (pHead2 === null) return pHead1;
if (pHead1.val <= pHead2.val) {
pHead1.next = Merge(pHead1.next, pHead2);
return pHead1;
} else {
pHead2.next = Merge(pHead1, pHead2.next);
return pHead2;
}
}