不创建新链
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode dumpy;
ListNode *l3 = &dumpy;
while(l1 && l2){
if(l1->val <l2->val){
l3->next = l1;
l1= l1->next;
}
else {
l3->next = l2;
l2 = l2->next;
}
l3 = l3->next;
}
l3->next = l1? l1 : l2;
return dumpy.next;
}
};
创建新链
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode dumpy;
ListNode *l3 = & dumpy;
while(l1 && l2){
int val = min(l1->val,l2->val);
l1->val < l2->val ? l1 = l1->next : l2 = l2->next;
l3->next = new ListNode(val);
l3 = l3->next;
}
ListNode *l = l1?l1:l2;
while(l){
l3->next = new ListNode(l->val);
l = l->next;
l3 = l3->next;
}
return dumpy.next;
}
};
递归版本
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(!l1) return l2;
if(!l2) return l1;
ListNode *head;
if(l1->val < l2->val){
head = l1;
head->next = mergeTwoLists(l1->next,l2);
}
else {
head = l2;
head ->next = mergeTwoLists(l1,l2->next); //此处l2->next可以换成head->next,因为他们指向同一个内存单元,上面那个也是
}
return head;
}
};