传送门
nowcoder
leetcode
题目描述
输入两个递增的链表,单个链表的长度为n,
合并这两个链表并使新链表中的节点仍然是递增排序的。
数据范围:0 <= n <= 1000,-1000 <= 节点数 <= 1000
要求:空间复杂度O(1),时间复杂度O(n)
C++ 代码 - nowcoder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { if (pHead1 == nullptr) return pHead2; if (pHead2 == nullptr) return pHead1;
if (pHead1->val > pHead2->val) swap(pHead1, pHead2); pHead1->next = Merge(pHead1->next, pHead2); return pHead1; } };
class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { if (pHead1 == nullptr) return pHead2; if (pHead2 == nullptr) return pHead1;
ListNode *dummy = new ListNode(-1), *p = dummy; while (pHead1 != nullptr && pHead2 != nullptr) {
if (pHead1->val > pHead2->val) swap(pHead1, pHead2); p->next = pHead1; pHead1 = pHead1->next; p = p->next; } p->next = (pHead1 ? pHead1 : pHead2); return dummy->next; } };
|
C++ 代码 - leetcode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
class Solution { public: ListNode* trainningPlan(ListNode* l1, ListNode* l2) { ListNode* dummy = new ListNode(-1); ListNode *p = dummy, *p1 = l1, *p2 = l2;
while (p1 != nullptr && p2 != nullptr) { if (p1->val <= p2->val) { p->next = p1; p1 = p1->next; } else { p->next = p2; p2 = p2->next; } p = p->next; } p->next = (p1 != nullptr) ? p1 : p2; return dummy->next; } };
|