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.
pro:将两个排好序的链表merge。新链表不能是新建的节点,应该是原来节点的拼接。
sol:题目中说了不能新建。merge其实就是排序链表的归并。好像链表的归并真的不需要额外的空间,恍然大悟。之前有一道Sort List没想明白,其实不需要每次new 一个节点的。只用找一个小的做表头再递归merge就好了。
code:
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if(l1==NULL&&l2==NULL) return NULL;
ListNode *res = solve(l1,l2);
return res;
}
ListNode *solve(ListNode *l1,ListNode *l2)
{
if(l1==NULL) return l2;
if(l2==NULL) return l1;
if(l1->val<l2->val)
{
l1->next=solve(l1->next,l2);
return l1;
}else
{
l2->next=solve(l1,l2->next);
return l2;
}
}
}