将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
===============================================================================
时间复杂度O(n+m),空间复杂度为O(1)
class Solution { public: ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) { ListNode *m = NULL; ListNode *p = NULL; if (list1 == NULL) return list2; if (list2 == NULL) return list1; ListNode *h1; ListNode *h2; list1->val > list2->val ? h1 = list2 : h1 = list1; list1->val > list2->val ? h2 = list1 : h2 = list2; m = h1; while (h1 != NULL) { if (h2 != NULL) { if (h1->next&&h1->next->val <= h2->val) { h1 = h1->next; } else { p = h2; h2 = h2->next; p->next = h1->next; h1->next = p; h1 = h1->next; } } else break; } return m; } };
看题解,有递归的写法,真的简便,帅气
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (l1 == nullptr) { return l2; } else if (l2 == nullptr) { return l1; } else 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) { ListNode* preHead = new ListNode(-1); ListNode* prev = preHead; while (l1 != nullptr && l2 != nullptr) { if (l1->val < l2->val) { prev->next = l1; l1 = l1->next; } else { prev->next = l2; l2 = l2->next; } prev = prev->next; } prev->next = l1 == nullptr ? l2 : l1; return preHead->next; } };
最后晒一下我的方法的性能