题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <cstddef> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pHead1 ListNode类 * @param pHead2 ListNode类 * @return ListNode类 */ ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { // write code here if(pHead1==NULL) return pHead2; if(pHead2 == NULL) return pHead1; ListNode * temp1 = pHead1, * pre1 = NULL; ListNode * temp2 = pHead2; while (temp1!=NULL and temp2 !=NULL) { if(temp1->val < temp2->val){ pre1 = temp1; temp1 = temp1 ->next; } else{ if(pre1==NULL){ pHead1 = temp2; } ListNode * tt = temp2 ->next; temp2 ->next = temp1; if(pre1==NULL){ pre1 = temp2; }else{ pre1 ->next = temp2; } pre1 = temp2; temp2 = tt; } } if(temp2!=NULL){ pre1->next = temp2; } return pHead1; } };
⚠️:空间复杂度是o(1)说明不能引入新的空间
要注意点就是 如果开头是list2的内容,那么return pHead1; 要处理好
当退出时 只有temp2不为空才需要借上,因为本身list1的东西打印pHead1都还在