My 24 ms code in C


  • 0
    X
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode root;
        struct ListNode *prev = &root;
        struct ListNode *n, *single;
        int temp, cnt, mod;
        cnt = 0;
        if (l1 == NULL && l2 == NULL) return NULL;
        if (l1 == NULL) return l2;
        if (l2 == NULL) return l1;
        while(l1 || l2) {
            n = malloc(sizeof(struct ListNode));
            temp = cnt;
            if (l1) temp += l1->val;
            if (l2) temp += l2->val;
            cnt = temp / 10;
            mod = temp % 10;
            n->val = mod;
            prev->next = n;
            prev = n;
            if (l1) l1 = l1->next;
            if (l2) l2 = l2->next;
        }
        if (cnt) {
            n = malloc(sizeof(struct ListNode));
            n->val = cnt;
            n->next = NULL;
            prev->next = n;
        } else {
            prev->next = NULL;
        }
        return root.next;
    }

Log in to reply
 

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