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.
The easiest way is to use recursion.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
ListNode* p=NULL; | |
if(l1==NULL) | |
return l2; | |
if(l2==NULL) | |
return l1; | |
if(l1->val<l2->val){ | |
p=l1; | |
l1=l1->next; | |
p->next=mergeTwoLists(l1, l2); | |
}else{ | |
p=l2; | |
l2=l2->next; | |
p->next=mergeTwoLists(l1, l2); | |
} | |
return p; | |
} | |
}; |
No comments:
Post a Comment