要求:空间复杂度 O(1) ,时间复杂度 O(n) 。
方法1:新链表合并,抄自牛客题解。比较直观。
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
auto vhead=new ListNode(-1); //设置一个哨兵指针
ListNode *newhead=vhead;
while(pHead1&&pHead2)
{
if(pHead1->val <= pHead2->val){
newhead->next = pHead1;
pHead1 = pHead1->next;
}else{
newhead->next = pHead2;
pHead2 = pHead2->next;
}
newhead = newhead->next;
}
if(pHead2==nullptr)
newhead->next=pHead1;
if(pHead1==nullptr)
newhead->next=pHead2;
return vhead->next;
}
};
方法2:递归。时间复杂度:O(m+n);空间复杂度:O(m+n)。
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (!pHead1) return pHead2;
if (!pHead2) return pHead1;
if (pHead1->val <= pHead2->val) {
pHead1->next = Merge(pHead1->next, pHead2);
return pHead1;
}
else {
pHead2->next = Merge(pHead1, pHead2->next);
return pHead2;
}
}
};