/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { ListNode* ans = new ListNode(-1); ListNode* cur = ans; while (pHead1 != nullptr && pHead2 != nullptr) { ListNode* tmp = new ListNode(-1); if (pHead1->val < pHead2->val) { tmp->val = pHead1->val; pHead1 = pHead1->next; } else { tmp->val = pHead2->val; pHead2 = pHead2->next; } cur->next = tmp; cur = cur->next; } // 注意这里 别忘 更新两个指针 while (pHead1 != nullptr) { cur->next = pHead1; cur = cur->next; pHead1 = pHead1->next; } while (pHead2 != nullptr) { cur->next = pHead2; pHead2 = pHead2->next; cur = cur->next; } return ans->next == nullptr ? nullptr : ans->next; } };
太容易大意