C solution


  • 0
    D
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* add(struct ListNode* l1, struct ListNode* l2, int i) {
        if (l2 != NULL || l1 != NULL || i != 0) {
            if (l2 == NULL) {
                l2 = (struct ListNode*)malloc(sizeof(struct ListNode));
                l2 -> val = 0;
                l2 -> next = NULL;
            }
            if (l1 == NULL) {
                l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
                l1 -> val = 0;
                l1 -> next = NULL;
            }
            struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
            int num = l1 -> val + l2 -> val + i;
            node -> val = num % 10;
            node -> next = add(l1 -> next, l2 -> next, num / 10);
            return node;
        }
        return NULL;
    }
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode* result = (struct ListNode*) malloc(sizeof(struct ListNode));
        result = add(l1, l2, 0);
        return result;
    }

Log in to reply
 

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