参考代码1
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == nullptr)
return l2;
if(l2 == nullptr)
return l1;
ListNode* res = new ListNode(-1); //这里申请了一个值为-1的节点,返回的是它的下一个节点开始的链表
ListNode* cur = res; //用cur指向该节点,并用cur来变化,注意左右顺序
while(l1 && l2) {
if( l1->val <= l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = (l1!=nullptr) ? l1 : l2; //有一个链表遍历结束,将当前的下一个节点链接到没遍历完的链表
return res->next;
}
};
参考代码2(递归)
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2){
if(l1 == nullptr)
return l2;
if(l2 == nullptr)
return l1;
if( l1->val <= l2->val) {
l1->next = mergeTwoLists(l1->next,l2);
return l1;
} else {
l2->next = mergeTwoLists(l1,l2->next);
return l2;
}
}
};
参考:https://www.cnblogs.com/grandyang/p/4086297.html