Posted on

Description

Submission

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* res = nullptr;
        ListNode* p = res;
        for(ListNode *p1 = l1, *p2 = l2; p1 != nullptr || p2 != nullptr; ) {
            if(res == nullptr) {
                res = new ListNode();
                p = res;
            } else {
                p->next = new ListNode();
                p = p->next;
            }
            if(p1 == nullptr) {
                p->val = p2->val;
                p2 = p2->next;
            } else if(p2 == nullptr) {
                p->val = p1->val;
                p1 = p1->next;
            } else {
                if(p1->val < p2->val) {
                    p->val = p1->val;
                    p1 = p1->next;
                } else {
                    p->val = p2->val;
                    p2 = p2->next;
                }
            }
            
        }
        return res;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *