题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { ListNode* res = nullptr; //边界情况 if (pHead1 == nullptr || pHead2 == nullptr) { if(pHead1 == nullptr && pHead2 != nullptr) return pHead2; if(pHead1 != nullptr && pHead2 == nullptr) return pHead1; if(pHead1 == nullptr && pHead2 == nullptr) return res; } //尾插最大值 ListNode* newnode = new ListNode(1001); ListNode* newnode1 = new ListNode(1001); ListNode* p1 = pHead1; ListNode* p2 = pHead2; while (p1->next != nullptr) p1 = p1->next; while (p2->next != nullptr) p2 = p2->next; p1->next = newnode; p2->next = newnode1; // while (pHead1->next != nullptr || pHead2->next != nullptr) { if (pHead1->val < pHead2->val) { ListNode* newnode = new ListNode(pHead1->val); pHead1 = pHead1->next; if (res == nullptr) { res = newnode; } else { ListNode* ptemp = res; while (ptemp->next != nullptr) ptemp = ptemp->next; ptemp -> next = newnode; } } else if (pHead1->val > pHead2->val) { ListNode* newnode = new ListNode(pHead2->val); pHead2 = pHead2->next; if (res == nullptr) { res = newnode; } else { ListNode* ptemp = res; while (ptemp->next != nullptr) ptemp = ptemp->next; ptemp -> next = newnode; } } else { ListNode* newnode = new ListNode(pHead2->val); ListNode* newnode1 = new ListNode(pHead2->val); newnode->next = newnode1; pHead1 = pHead1->next; pHead2 = pHead2->next; if (res == nullptr) { res = newnode; } else { ListNode* ptemp = res; while (ptemp->next != nullptr) ptemp = ptemp->next; ptemp -> next = newnode; } } } return res; } };
尾插最大值
不断地尾插