您的位置:首页 > 编程语言 > C语言/C++

leetcode #21 in cpp

2016-05-22 04:24 585 查看
The question is to merge two sorted linked list into one sorted linked list.

Solution: 

Solution 1. Use recurrence. 

The recurrence structure is as following: 

ListNode* merge(ListNode *l1, ListNode *l2){

1. initialize ListNode * head = min(l1->val, l2->val).

2. head->next = merge(new_l1, new_l2)   //(new_l1 = l1->next if l1->val < l2 ->val, otherwise new_l1 = l1; new_l2 = l2->next if l2->val < l1->val, otherwise new_l2 = l2.)

3. return head;

}  

Code: 

/**
* 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) return l2;
if(!l2) return l1;
ListNode *head = new ListNode(l1->val<l2->val?l1->val:l2->val);
head->next = mergeTwoLists(l1->val<l2->val?l1->next:l1,l1->val<l2->val?l2:l2->next);
return head;
}
};


Solution 2: Use iterations. Basically it is the same as recurrence, but with loops rather than recurrence call. 

Code: 

 ListNode *l3 = new ListNode(0); 
        ListNode *head = l3;
        if(l1==NULL) return l2;
        if(l2==NULL) return l1;
        while(l1!=NULL && l2 != NULL){
            l3->next = new ListNode(0);
            l3 = l3->next;
            l3->val = l1->val > l2->val ?l2->val:l1->val;
            l1->val > l2->val ?l2 = l2->next:l1 = l1->next;
        }
        if(l1 == NULL && l2 == NULL) return head->next;
        l3->next = new ListNode(0);
        l3->next = l1 == NULL ?l2:l1;
        return head->next; 



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode cpp