思路:和归并排序一样就行了
/**
* 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&&l2==NULL) return NULL;
ListNode *head;
if(l1==NULL) {
head=new ListNode(l2->val);
head->next=mergeTwoLists(l1,l2->next);
}
else if(l2==NULL) {
head=new ListNode(l1->val);
head->next=mergeTwoLists(l1->next,l2);
}
else {
if((l2->val)>(l1->val)){
head=new ListNode(l1->val);
head->next=mergeTwoLists(l1->next,l2);
}else {
head=new ListNode(l2->val);
head->next=mergeTwoLists(l1,l2->next);
}
}
return head;
}
};