3 lines C++ (12ms) and C (4ms)


  • 21

    C++

    The first line ensures that a is at least as good a list head as b, by swapping them if that's not already the case. The second line merges the remaining lists behind a.

    ListNode* mergeTwoLists(ListNode* a, ListNode* b) {
        if (!a || b && a->val > b->val) swap(a, b);
        if (a) a->next = mergeTwoLists(a->next, b);
        return a;
    }
    

    C

    Same solution, I just have to replace C++'s swap. I'm not sure whether evaluation order is standardized, but it worked and got accepted this way.

    struct ListNode* mergeTwoLists(struct ListNode* a, struct ListNode* b) {
        if (!a || b && a->val > b->val) a += b - (b = a);
        if (a) a->next = mergeTwoLists(a->next, b);
        return a;
    }

  • 0
    M

    I'm a little confused of this code "a += b - (b = a)", Can you pleas explain it?


  • 0
    S

    Even I tried this on my computer "a += b - (b = a)" is not working.

    May be he tried to below. but how does his code works for swapping?

    // Code to swap 'x' and 'y'
    x = x + y;
    y = x - y;
    x = x - y;


  • 0

    @Mxiaoyu You can consider that line as a= a + ( b - ( b = a ));


Log in to reply
 

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