
/**
* 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* dummy = new ListNode(-1);
ListNode* tail = dummy;
while (l1 && l2)
{
if (l1->val < l2->val)
{
tail = tail->next = l1;
l1 = l1->next;
} else {
tail = tail->next = l2;
l2 = l2->next;
}
}
if (l1) tail->next = l1;
if (l2) tail->next = l2;
return dummy->next;
}
};
本文介绍了如何使用C++解决LeetCode中的第21题——合并两个有序链表。通过详细讲解代码逻辑,阐述了如何高效地合并两个已排序的链表,达到线性时间复杂度。
695

被折叠的 条评论
为什么被折叠?



