合并有序链表
将两个升序链表合并为一个新的 升序 链表并返回。
新链表是通过拼接给定的两个链表的所有节点组成的。
[https://leetcode-cn.com/problems/merge-two-sorted-lists/](LeetCode 21)
//方法1、迭代
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1NULL)
return l2;
if(l2NULL)
return l1;
ListNode* temp=new ListNode(0);
ListNode* head=temp;
while(l1&&l2){
if(l1->val<=l2->val){
temp->next=l1;
l1=l1->next;
}
else{
temp->next=l2;
l2=l2->next;
}
temp=temp->next;
}
if(l1==NULL){
temp->next=l2;
}
else
temp->next=l1;
return head->next;
}
};
//方法2、递归
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1NULL)
return l2;
if(l2NULL)
return l1;
if(l1->val<l2->val){
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}
else{
l2->next=mergeTwoLists(l1,l2->next);
return l2;
}
}
};

浙公网安备 33010602011771号