21. Merge Two Sorted Lists

问题描述

解决方案

非递归方式

/**
 * 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) return l2;
        if(l2==NULL) return l1; 
        ListNode* ml;
        ml->next=NULL;
        ListNode* rml =ml;
        while(l1&&l2)
        { 
            if(l1->val>l2->val) 
            { 
                ml->next=l2;
                l2=l2->next;
            }
            else
            { 
                ml->next=l1;
                l1=l1->next;
            }
            ml=ml->next;
        }  
        if(!l1) ml->next=l2;
        if(!l2) ml->next=l1;
        return rml->next;
    }
};

递归方式

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(!l1||!l2) return l1?l1:l2;
        else if(l1->val>l2->val)
        {
            l2->next=mergeTwoLists(l1,l2->next);
            return l2;
        }
        else 
        {
            l1->next=mergeTwoLists(l1->next,l2);
            return l1;
        }
    }
};
posted @ 2016-08-22 14:06  弦断  阅读(100)  评论(0编辑  收藏  举报