C clean, simple and uniform code solution


  • 0
    Y
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    static inline int getListSize(struct ListNode *const list) {
        int size = 0;
        for (struct ListNode *p = list; NULL != p; p = p->next) {
            size++;
        }
        return size;
    }
    
    static struct ListNode* move(const int length, struct ListNode *const list) {
        if (length < 0) return NULL;
        struct ListNode * p = list;
        for (int i = 0; i < length; i++)
            p = p->next;
        return p;
    }
    
    static void add(struct ListNode * dst, struct ListNode * const src) {
        if (NULL == dst->next) {
            // reach the end
            dst->val += src->val;
        } else {
            if (dst->next->val >= 10) {
                dst->next->val -= 10;
                dst->val += 1;
            }
            if (NULL == src) return;
            dst->val += src->val;
        }
    }
    
    static void append(struct ListNode ** head) {
        if ((*head)->val < 10) return;
        struct ListNode * tmp = calloc(1, sizeof(struct ListNode));
        (*head)->val -= 10;
        tmp->val = 1;
        tmp->next = *head;
        *head = tmp;
    }
    
    struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
        int s1 = getListSize(l1);
        int s2 = getListSize(l2);
        int i   = 0;
        int gap = 0;
        struct ListNode * destList = NULL;
        struct ListNode * srcList  = NULL;
        
        if (s1 < s2) {
            destList = l2;
            srcList  = l1;
            gap      = s2 - s1;
            i        = s2;
        } else {
            destList = l1;
            srcList  = l2;
            gap      = s1 - s2;
            i        = s1;
        }
        
        for (; i >= gap; i--) {
            struct ListNode * u = move(i-1, destList);
            struct ListNode * v = move(i-gap-1, srcList);
            if (NULL == u) continue;
            add(u, v);
        }
        for (; i > 0; i--) {
            struct ListNode * p = move(i-1, destList);
            if (p->next->val < 10) continue;
            p->next->val -= 10;
            p->val += 1;
        }
        append(&destList);
        return destList;
    }
    

Log in to reply
 

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