C++ code...


  • 0
    E

    =_=

    class Solution {
    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
            if(l1 == NULL)return l2;
            if(l2 == NULL)return l1;
            
            if(l1->val > l2->val){
                swap(l1, l2);
            }
            
            ListNode *p = l1, *q = l2, *tmp = NULL;
            while(p->next != NULL){
                if(p->next->val <= q->val){
                    p = p->next;
                }else{
                    swap(p, q); // p always points to the tail of the list 
                               // having been sorted
                    tmp = q->next;
                    q->next = p;
                    q = tmp;
                }
            }
            p->next = q;
            
            return l1;
        }
    };
    

Log in to reply
 

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