题目要求
解题思路
使用递归函数
返回l1指向的结点和l2指向的结点中值较小的结点,并将从下级函数获得的返回值,链接到当前结点尾部;当l1为空、或l2为空时,递归结束,返回l2或l1剩下的部分。
C++代码
/**
* 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) {
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
else
{
if(l1->val<l2->val)
{
l1->next=mergeTwoLists(l1->next,l2);
return l1;
}
else
{
l2->next=mergeTwoLists(l2->next,l1);
return l2;
}
}
}
};
执行结果