剑指 Offer 25 合并两个排序的链表
概述
https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
https://leetcode.com/problems/merge-two-sorted-lists/
递归法
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (!l1) return l2;
if (!l2) return l1;
if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
迭代法
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
auto dummyHead = new ListNode;
auto c = dummyHead;
while (l1 && l2) {
if (l1->val < l2->val) {
c->next = l1;
l1 = l1->next;
} else {
c->next = l2;
l2 = l2->next;
}
c = c->next;
}
if (l1) {
c->next = l1;
} else {
c->next = l2;
}
return dummyHead->next;
}
};
Links: sword-offer-25