mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-08-06 18:24:23 +08:00
1.9 KiB
1.9 KiB
更多精彩文章持续更新,微信搜索「代码随想录」第一时间围观,本文https://github.com/youngyangyang04/TechCPP 已经收录,里面有更多干货等着你,欢迎Star!
题目地址
https://leetcode-cn.com/problems/merge-two-sorted-lists/
思路
链表的基本操作,一下代码中有详细注释
代码
/**
* 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:
// 题目中我们为什么定义了一个 新的head
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head = new ListNode();
ListNode* index = head;
while(l1 != nullptr && l2 != nullptr) { // 注意null 和nullptr的区别
if (l1->val < l2->val) {
index->next = l1;
l1 = l1->next;
} else {
index->next = l2;
l2 = l2->next;
}
index = index->next;
}
if (l1 != nullptr) {
index->next = l1;
l1 = l1->next;
}
if (l2 != nullptr) {
index->next = l2;
l2 = l2->next;
}
ListNode* tmp = head; // 注意清理内存,不清理也没事
head = head->next;
delete tmp;
return head;
// return head->next
}
};
更过算法干货文章持续更新,可以微信搜索「代码随想录」第一时间围观,关注后,回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等,就可以获得我多年整理的学习资料。