leetcode21 C++ 8ms 合并两个有序链表

/**
 * 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;
    }
};
posted @ 2018-07-24 18:16  一条图图犬  阅读(842)  评论(0编辑  收藏  举报