LintCode 合并两个排序

将两个排序链表合并为一个新的排序链表

样例

给出 1->3->8->11->15->null2->null, 返回1->2->3->8->11->15->null

分析 :与剑指Offer上的一道一样。 递归

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param ListNode l1 is the head of the linked list
     * @param ListNode l2 is the head of the linked list
     * @return: ListNode head of linked list
     */
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        // write your code here
        if(l1==NULL)
        return l2;
        else if(l2==NULL)
        return l1;
        
        ListNode *mergehead;
        if(l1->val<l2->val)
        {
            mergehead=l1;
            mergehead->next=mergeTwoLists(l1->next,l2);
        }
        else
        {
             mergehead=l2;
            mergehead->next=mergeTwoLists(l1,l2->next);
        }
        return mergehead;
    }
};

  

原文地址:https://www.cnblogs.com/lelelelele/p/6117636.html