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.
思路:对于两个list而言,我们需要找到按照大小顺序将这两个list合并起来,然后返回这个新的list,对于这个问题,我们用下面这个例子来表示:
list1 | list2 | result |
---|---|---|
1,2,3,4 | 2,5 | 1,2,2,3,4,5 |
在这里我们用递归的方法来求解:
代码:
#include<iostream>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){}
};
ListNode* merge2lists(ListNode *l1,ListNode *l2){
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
if(l1->val < l2->val){
l1->next = merge2lists(l1->next,l2);
return l1;
}else{
l2->next = merge2lists(l1,l2->next);
return l2;
}
}
int main(){
ListNode a = ListNode(1);
ListNode b = ListNode(2);
ListNode c = ListNode(3);
ListNode d = ListNode(4);
ListNode e = ListNode(2);
ListNode f = ListNode(5);
a.next = &b;
b.next = &c;
c.next = &d;
e.next = &f;
ListNode *res = merge2lists(&a,&e);
while(res != NULL){
cout<<res->val<<endl;
res = res->next;
}
}
运行时间: O(n)