題目
將兩個升序鏈表合併爲一個新的升序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
示例:
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
//cpp
class Solution {
public:
ListNode* mergeTwoLists(ListNode* n1, ListNode* n2) {
ListNode dummy (0) ;
ListNode* start= &dummy ;
while(n1 && n2)
{
if(n1->val <= n2->val)
{
start->next = n1;
n1 = n1->next;
}
else
{
start->next = n2;
n2 = n2->next;
}
start = start->next;
}
start->next = n1 ? n1 : n2 ; //剩餘部分的加入
return dummy.next;
}
};
#python
class Solution:
def mergeTwoLists(self, l1, l2):
if l1 is None:
return l2
elif l2 is None:
return l1
elif l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2