C++ iterative linear runtime


  • 0
    M
    /**
     * 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) {
            
            // first check if either list is empty
            if(l1==NULL) return l2;
            if(l2==NULL) return l1;
            // if both lists contain at least 1 element, establish "start" element for result
            ListNode* start = NULL;
            if(l1->val < l2->val) {
                start = l1;
                l1 = l1->next;
            }
            else {
                start = l2;
                l2 = l2->next;
            }
            // use a pointer to loop thru heads of both lists in order
            ListNode* curr = start;
            while(l1!=NULL && l2!=NULL) {
                if(l1->val < l2->val) {
                    curr->next = l1;
                    l1 = l1->next;
                }
                else {
                    curr->next = l2;
                    l2 = l2->next;
                }
                curr = curr->next;
            }
            // until this point, either l1 or l2 should be empty, one last operation to link the remaining one to tail
            if(l1!=NULL) curr->next = l1;
            if(l2!=NULL) curr->next = l2;
            return start;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.