题解 | #合并两个排序的链表#
合并两个排序的链表
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) { // write code here if(pHead1 == nullptr || pHead2 == nullptr) return pHead1==nullptr ?pHead2 :pHead1; ListNode* head = pHead1->val <= pHead2->val ? pHead1 : pHead2; ListNode* cur1 = head->next; ListNode* cur2 = head == pHead1 ? pHead2 : pHead1; ListNode* pre = head; while(cur1!=nullptr && cur2!=nullptr) { if(cur1->val <= cur2->val) { pre->next =cur1; cur1=cur1->next; } else{ pre->next =cur2; cur2=cur2->next; } pre = pre->next; } pre->next = cur1!=nullptr ? cur1 : cur2; return head; } }; // ↓cur2 // List1 2 4 6 // ↓cur1 // List2 1 3 5 7 8 // ↓ // head(pre)