合并两个有序链表

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

        head->next = l1 != nullptr ? l1: l2;
        return res;
    }
};
原文地址:https://www.cnblogs.com/zhousong918/p/10174688.html