1. 问题描述
2. 样例说明
3. 迭代版本求解
3.1 算法思想
初始化:定义cur指向新链表的头结点
操作:
(1)如果L1指向的结点值小于等于L2指向的结点值,则将L1指向的结点值链接到cur的next指针,然后L1指向下一个结点值。否则,让L2指向下一个结点值
(2)循环步骤1,直到L1或者L2为nullptr
(3)将L1或者L2剩下的部分链接到cur的后面
3.2 代码
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
ListNode *h=new ListNode(-1);
ListNode *cur=h;
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 h->next;
}
};
3.3 时间空间复杂度分析
时间复杂度:O(m+n),m、n分别为两个单链表的长度
空间复杂度:O(1)
4. 递归版本求解
4.1 算法思想
4.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;
}
}
};
4.3 时间空间复杂度分析
时间复杂度:O(m+n)
空间复杂度:O(m+n),每一次递归,递归栈都会保存一个变量,最差情况会保存(m+n)个变量