My C version Solution


  • 0
    W
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode *pHead, *pTail, *p;
        pHead = (struct ListNode*)malloc(sizeof(struct ListNode));
        pHead->next = NULL;
        p = pTail = pHead;
        int carry = 0;
        while(l1 || l2)
        {
            p = (struct ListNode*)malloc(sizeof(struct ListNode));
            p->next = NULL;
            p->val = (l1?l1->val:0) + (l2?l2->val:0) + carry;
            carry = p->val / 10;
            p->val %= 10;
            pTail->next = p;
            pTail = p;
            l1 = l1?l1->next:NULL;
            l2 = l2?l2->next:NULL;
        }
        if(carry)
        {
            p = (struct ListNode*)malloc(sizeof(struct ListNode));
            p->next = NULL;
            p->val = 1;
            pTail->next = p;
            pTail = pTail->next;
        }
        return pHead->next;
    }
    

Log in to reply
 

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