题目相关
【题目解读】
合并两个有序列表,并返回新列表。
【原题描述】原题链接
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
【难度】Easy
Solution
不带头结点
最开始的解法,不带头结点的链表,处理起来有点麻烦,需要先判断,是否是第一个节点,所以有如下解法
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
ListNode *head, *p;
head = p = NULL;
bool isHead = true; // 单独处理head
while (l1 != NULL && l2 != NULL)
{
if (l1->val <= l2->val)
{
if (isHead)
{
p = l1;
head = p;
isHead = false;
l1 = l1->next;
}
else
{
p->next = l1;
p = p->next;
l1 = l1->next;
}
}
else
{
if (isHead)
{
p = l2;
head = p;
l2 = l2->next;
isHead = false;
}
else
{
p->next = l2;
p = p->next;
l2 = l2->next;
}
}
} // end while
while (l1 != NULL)
{
if (isHead)
{
p = l1;
head = p;
l1 = l1->next;
isHead = false;
}
else
{
p->next = l1;
l1 = l1->next;
p = p->next;
}
}
while (l2 != NULL)
{
if (isHead)
{
p = l2;
head = p;
l2 = l2->next;
isHead = false;
}
else
{
p->next = l2;
p = p->next;
l2 = l2->next;
}
}
return head;
}
增加头结点
其实可是增加一个头结点,返回的时候不返回头结点,这样算法也能极大的简化。
代码:
ListNode *mergeTwoLists_head(ListNode *l1, ListNode *l2)
{
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;
ListNode head(0);
ListNode *p = &head;
while (l1 != NULL && l2 != NULL)
{
if (l1->val <= l2->val)
{
p->next = l1;
l1 = l1->next;
}
else
{
p->next = l2;
l2 = l2->next;
}
p = p->next;
} // end while
if (l1 != NULL)
p->next = l1;
if (l2 != NULL)
p->next = l2;
return head.next;
}
运行结果:
![](https://i-blog.csdnimg.cn/blog_migrate/455e0ad946f86ea07566508a3a2ff37d.png)
使用递归
ListNode *mergeTwoLists_recursion(ListNode *l1, ListNode *l2)
{
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
if (l1->val <= l2->val)
{
l1->next = mergeTwoLists_recursion(l1->next, l2);
return l1; //该if语句的结果需要返回
}
else
{
l2->next = mergeTwoLists_recursion(l1, l2->next);
return l2;
}
}
运行结果:
![](https://i-blog.csdnimg.cn/blog_migrate/bf6e529b6fd8904f988226eb85e31087.png)