Concise C++ iterative solution


  • 0
    S
    class Solution {
    public:
        ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
            
            ListNode dummy(-1);
            ListNode *tail = &dummy;
            
            ListNode *p1 = l1;
            ListNode *p2 = l2;
            while(p1 || p2)
            {
                if(p2 == NULL || (p1 && p2 && p1->val < p2->val))
                {
                    tail->next = p1;
                    tail = p1;
                    p1 = p1->next;
                }
                else
                {
                    tail->next = p2;
                    tail = p2;
                    p2 = p2->next;
                }
            }
            tail->next = NULL;
            return dummy.next;
        }
    };

Log in to reply
 

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