My 20ms solutions in C


  • 0
    H

    /**
    * Definition for singly-linked list.
    * struct ListNode {
    * int val;
    * struct ListNode *next;
    * };
    */

    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        struct ListNode* ptrL1 = l1;
        struct ListNode* ptrL2 = l2;
        struct ListNode* headSum = NULL;
        struct ListNode* prvSum = NULL;
        struct ListNode* curSum = NULL;
        bool carry = false;
        int tmpSum = 0;
        
        while(ptrL1 != NULL || ptrL2 != NULL) {
    
            if(ptrL1 != NULL && ptrL2 != NULL) {
                tmpSum = ptrL1->val + ptrL2->val;
                ptrL1 = ptrL1->next;
                ptrL2 = ptrL2->next;
            }
            else if(ptrL1 != NULL) {
                tmpSum = ptrL1->val;
                ptrL1 = ptrL1->next;
            }
            else if(ptrL2 != NULL) {
                tmpSum = ptrL2->val;
                ptrL2 = ptrL2->next;
            }
            
            curSum = (struct ListNode*)malloc(sizeof(struct ListNode));
            if(curSum != NULL) {
                tmpSum += carry ? 1 : 0;
                curSum->val = tmpSum % 10;
                curSum->next = NULL;
                if(prvSum != NULL) {
                    prvSum->next = curSum;
                }
                else {
                    headSum = curSum;
                    
                }
                prvSum = curSum;
                carry = tmpSum / 10;
            }
            else {
                break;
            }
        }
        
        //still got one carry after go through all, we need add one more node 
        if(carry) {
            curSum = (struct ListNode*)malloc(sizeof(struct ListNode));
            if(curSum != NULL) {
                curSum->val = 1;
                curSum->next = NULL;
                prvSum->next = curSum;
            }
        }
        
        return headSum;
    }

Log in to reply
 

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