{1,2,3,4,5,6}
初始化:定义cur指向新链表的头结点
操作:
/*
struct ListNode
{
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL)
{
}
};*/
class Solution
{
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
ListNode *vhead=new ListNode(-1); //初始化一个值为-1的节点
ListNode *cur=vhead;
if(pHead1==NULL)
{
return pHead2;
}
if(pHead2==NULL)
{
return pHead1;
}
while(pHead1&&pHead2)
{
if(pHead1->val<=pHead2->val)
{
cur->next =pHead1;
pHead1=pHead1->next;
}
else
{
cur->next=pHead2;
pHead2=pHead2->next;
}
cur=cur->next;
}
cur->next =pHead1?pHead1:pHead2;
return vhead->next;
}
};
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
函数功能:合并两个单链表,返回两个单链表头结点值小的那个节点。
如果知道了这个函数功能,那么接下来需要考虑2个问题:
代码:
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;
}
}
};
时间复杂度:O(m+n)
空间复杂度:O(m+n),每一次递归,递归栈都会保存一个变量,最差情况会保存(m+n)个变量
原文:https://www.cnblogs.com/LaiY9/p/14759875.html