1,题目要求
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.
也就是将两个单链表进行融合,变成一个单链表。
2,题目思路
对于这种类型,主要有两种思路:一种是利用递归的思想,依次比较链表中节点的值,直接将其融合成一个单链表;另外一种思想则不用递归,重新定义一个单链表,然后也是进行依次的比较,最后生成一个单链表。核心思想是一样的,只不过生成的过程略有差别。
题目最后的返回值是指向生成的单链表的第一个节点的指针。
3,程序源码
非递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
ListNode res(0);
ListNode *res_tail = &res;
while(l1 && l2)
{
if(l1->val <= l2->val)
{
res_tail->next = l1;
l1 = l1->next;
}
else
{
res_tail->next = l2;
l2 = l2->next;
}
res_tail = res_tail->next;
}
res_tail->next = l1 ? l1 : l2;
return res.next;
}
};
递归
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
if(l1 == nullptr)
return l2;
if(l2 == nullptr)
return l1;
while (l1!= nullptr && l2!= nullptr)
{
if(l1->val <= l2->val)
{
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else
{
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
}
};