题目描述
36.合并两个排序的链表
方法1
二路归并
时间复杂度
O(n)
C++ 代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2) {
auto dummy=new ListNode(-1),tail=dummy;
while(l1&&l2){
if(l1->val<l2->val){
tail=tail->next=l1;
l1=l1->next;
}
else{
tail=tail->next=l2;
l2=l2->next;
}
}
if(l1)
tail->next=l1;
if(l2)
tail->next=l2;
//tail->next=(l1!=NULL ? l1:l2);
return dummy->next;
}
};
方法2
递归
C++ 代码
class Solution{
public:
ListNode* merge(ListNode* l1,ListNode* l2){
if(l1==NULL) return l2;
if(l2==NULL) return l1;
if(l1->val<=l2->val){
//l1的下个结点指向将其他结点合并后的头结点
l1->next=merge(l1->next,l2);
return l1;
}
else{
l2->next=merge(l1,l2->next);
return l2;
}
}
};