题目描述
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所 有节点组成的。
示例
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
思路
我们可以递归地定义两个链表里的 mergeTwoLists操作,也就是说,两个链表头部值较小的一个节点与剩下元素的 mergeTwoLists操作结果合并。
递归法
struct ListNode {
int value;
ListNode *next;
}ListNode;
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL)return l2;//如果任一链表为空链表,直接返回另一个链表
if(l2 == NULL)return l1;
if(l1->value < l2->value)
{
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else
{
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}