新建一个h结点作为新链表的头(哨兵结点),要new不要初始化为nullptr,来一个cur来在链表上移动。遍历两条链表,只要一条空就结束遍历,用cur的next指向未空的另一条链表即可。将比较小的那个结点直接拷贝构造,是深拷贝等于新建一个结点,而不是指向l1,不然会改变l1的指向。并将cur指向next,l1也往后走一步。l2同理。最后返回哨兵的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 == nullptr) return l2;
if(l2 == nullptr) return l1;
//链表=双指针=空间鲁棒性
//两个指针分别在两点链表上走,找到比较小的就用其作为新结点
ListNode* h = new ListNode(0);
ListNode* cur = h;
while(l1 != nullptr && l2 !=nullptr){
if(l1->val <= l2->val){
cur->next = l1;
l1 = l1->next;
cur = cur->next;
}
else{
cur->next = l2;
l2 = l2->next;
cur = cur->next;
}
}
cur->next = l1==nullptr ? l2:l1;
return h->next;
}
};
二刷,简单的merge
/**
* 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 == nullptr) return l2;
if(l2 == nullptr) return l1;
//用新建的方式,不能在原链表上乱改的
//h是哨兵,cur一直往后移动
ListNode* h = new ListNode(0);
ListNode* cur = h;
while(l1 != nullptr && l2 != nullptr){
if(l1->val <= l2->val){
cur->next = l1;
l1 = l1->next;
}
else{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if(l1 == nullptr){
cur->next = l2;
}
else if(l2 == nullptr){
cur->next = l1;
}
return h->next;
}
};
递归版本才要记住。
每次返回的是结果链表的下一个结点,如果有一条为空了直接返回另外一条的全部剩下的就行了
l1比l2小,所以返回l1,所以我们要改变l1后面的,保证返回它的时候后面已经被全部定义好了
/**
* 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 == nullptr) return l2;
if(l2 == nullptr) return l1;
if(l1->val <= l2->val){
//l1比l2小,所以返回l1,所以我们要改变l1后面的,保证返回它的时候后面已经被全部定义好了
l1->next = mergeTwoLists(l1->next,l2);
return l1;
}
else{
l2->next = mergeTwoLists(l1,l2->next);
return l2;
}
}
};