Thursday, January 28, 2016

LeetCode Q21: Merge two sorted lists

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.

/**
* 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