天天看點

【2019秋冬】【LeetCode】21 合并兩個有序連結清單

/**
 * 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) {
        ListNode* an = new ListNode(0);
        ListNode* ans = an;
        if(l1==NULL && l2==NULL) return NULL;
        while(l1 != NULL || l2 != NULL){
            if( l2==NULL|| ( l1!=NULL&& (l1->val < l2->val)) ){
                ans->next = l1;
                ans = ans->next;
                l1 = l1->next;
                continue;
            }
            if( l1==NULL || (l2!=NULL&&(l2->val <= l1->val))){
                ans->next = l2;
                ans = ans->next;
                l2 = l2->next;
                continue;
            }         
        }
        return an->next;
    }
};
           

注意這個或條件的順序,否則LeetCode會報錯,說可能存在調用空指針隐患