/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!l1||!l2) {
return NULL;
}
ListNode *head= NULL;
ListNode *res= head;
ListNode *prev= head;
while (l1 && l2) {
if (l1->val < l2->val) {
res= l1;
l1=l1->next;
prev->next=res;
prev=res;
}else {
res= l2;
l2=l2->next;
prev->next=res;
prev=res;
}
}
if (l1!=NULL) {
res=l1;
} else if (l2!=NULL) {
res=l2;
}
return head;
}
};
Recursion
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (l1==NULL) return l2;
if (l2==NULL) return l1;
ListNode* res=NULL;
if (l1->val < l2->val) {
res=l1;
res->next=mergeTwoLists(l1->next, l2);
}else {
res=l2;
res->next=mergeTwoLists(l1,l2->next);
}
return res;
}
};