Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
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;
}
l2->next = mergeTwoLists(l2->next, l1);
return l2;
}
};
l1 = 1->2->4
l2 = 1->3->4
res = 1
l1 = 1->2->4
l2 = 3->4
res = 1->1
l1 = 2->4
l2 = 3->4
res = 1->1->2
l1 = 4
l2 = 3->4
res = 1->1->2->3
l1 = 4
l2 = 4
res = 1->1->2->3->4
l1 = 4
l2 = null
res = 1->1->2->3->4->4
l1 = null
l2 = null
实际执行过程为:
res = 4
res = 4->4
res = 3->4->4
res = 2->3->4->4
res = 1->2->3->4->4
res = 1->1->2->3->4->4