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
给定两个排好序的链表,按照顺序将他们合并到一起。对于链表和二叉树这种结构,递归基本是一种通解。下面我们来分析一下递归的过程:
1、返回条件:两链表其中之一为空时,返回不为空的那个链表的头节点;
2、递归条件:l1的值大于l2的时候,则合并后的新节点为l1的头节点,其下一个节点为l1->next和l2的合并结果;l1小于或等于l2的时候类比。
由此,可得到代码如下:
* 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* ret = merge(l1, l2);
return ret;
}
ListNode* merge(ListNode* l1, ListNode* l2)
{
if(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode* tmp;
if(l1->val < l2->val)
{
tmp = l1;
tmp->next = merge(l1->next, l2);
}
else
{
tmp = l2;
tmp->next = merge(l2->next, l1);
}
return tmp;
}
};