🥛迭代
类似与归并排序的合并函数,实际还要更简单一些,没有长度的限制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode nd(0), *pre = &nd; while(l1 || l2) { if(!l1) { pre->next = l2; l2 = l2->next; } else if(!l2) { pre->next = l1; l1 = l1->next; } else if(l1->val < l2->val) { pre->next = l1; l1 = l1->next; } else { pre->next = l2; l2 = l2->next; } pre = pre->next; } return nd.next; } };
|
Accepted
208/208 cases passed (8 ms)
Your runtime beats 93.28 % of cpp submissions
Your memory usage beats 76.07 % of cpp submissions (9 MB)
🥛递归
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(!l1) return l2; else if(!l2) return l1; else if(l2->val < l1->val) { l2->next = mergeTwoLists(l2->next, l1); return l2; } else { l1->next = mergeTwoLists(l1->next, l2); return l1; } } };
|
Accepted
208/208 cases passed (8 ms)
Your runtime beats 93.28 % of cpp submissions
Your memory usage beats 75.58 % of cpp submissions (9 MB)