A horrible hack in C [16ms]


  • 7
    A

    Allocating minimal amount memory by utilizing the passed in ListNode elements.

    Kids, don't do this at home, it is a very bad practice!

    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode* result = l1 ? l1 : l2;
        struct ListNode* carry = l1 ? l2 : l1;
        struct ListNode* node = result;
        struct ListNode* tmp;
        int c = 0;
        int s;
        while (l1 || l2) {
            s = c;
            if (l1) { s += l1->val; l1=l1->next; }
            if (l2) { s += l2->val; l2=l2->next; }
            c = s > 9 ? 1 : 0;
            node->val = c ? s - 10 : s;
            if (l1) {
                node = node->next = l1;
            } else if (l2) {
                node = node->next = l2;
            } else {
                node->next = NULL;
            }
        }
        if (c) {
            carry->val = c;
            node->next = carry;
            node = node->next;
        }
        node->next = NULL;
        return result;
    }

  • 0
    C

    Why horrible? I think you did a good job.


  • 0
    F

    because l1 and l2 is broken.


  • 0
    C

    Good solution, save much time of allocating memory

    I wrote a similar solution too


  • 0
    H

    aren't they formal parameters?


  • 0
    Y

    If the l1 and l2 are limited by "const",this way is not reatchable. But for this problem,you do a good job,and it is truly horrible.


Log in to reply
 

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