My Solution in C language, not graceful, but it works


  • 0
    R
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode* p = l1;
        struct ListNode* q = l2;
        struct ListNode* value = NULL;
        struct ListNode* r = NULL;
        int flag = 0, a = 0, b = 0;
        while(p != NULL || q != NULL) {
            a = (p == NULL)?0:p->val;
            b = (q == NULL)?0:q->val;
            struct ListNode* add = (struct ListNode*)malloc(sizeof(struct ListNode));
            add->val = (a+b+flag)%10;
            add->next = NULL;
            flag = (a+b+flag >= 0x0a)?1:0;
            if (r == NULL) {
                value = add;
                r = value;
            } else {
                r->next = add;
                r = r->next;
            }
            if (((p != NULL && q != NULL && p->next == NULL && q->next == NULL) ||
                (p == NULL || q == NULL)) && flag == 1) {
                struct ListNode* add = (struct ListNode*)malloc(sizeof(struct ListNode));
                add->val = 1;
                add->next = NULL;
                r->next = add;
            }
            if (p != NULL) p = p->next;
            if (q != NULL) q = q->next;
        }
        return value;
    }

Log in to reply
 

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