题目:
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
解法:
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (!l1) return l2;
if (!l2) return l1;
if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
采用递归的写法,当某个链表为空了,就返回另一个。然后核心还是比较当前两个节点值大小,如果l1的小,那么对于l1的下一个节点和l2调用递归函数,将返回值赋值给l1.next,然后返回l1;否则就对于l2的下一个节点和l1调用递归函数,将返回值赋值给l2.next,然后返回l2。