[LeetCode] 2. Add Two Numbers

#include <stdlib.h>
#include <stdio.h>

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

struct ListNode {
     int val;
     struct ListNode *next;
};

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {

    int debug = 0;

    struct ListNode* cur1 = l1;
    struct ListNode* cur2 = l2;
    struct ListNode* l3 = malloc(sizeof(struct ListNode));
    l3->val = 0;
    l3->next = NULL;
    struct ListNode* tmp = l3;
    struct ListNode* cur3 = l3;

    int v1 = 0, v2 = 0, v3 = 0;
    int carry = 0, first = 1;
    while(cur1 != NULL || cur2 != NULL) {
        v1 = (cur1 == NULL ? 0 : cur1->val);
        v2 = (cur2 == NULL ? 0 : cur2->val);
        v3 = v1 + v2;
        
        if (carry == 1) {
            v3 += 1;
            carry = 0;
        }
        if(v3 > 9) {
            carry = 1;
            v3 -= 10;
        }
        tmp = malloc(sizeof(struct ListNode));
        tmp->val = v3;
        tmp->next = NULL;
        if(first == 1) {
            l3 = tmp;
            cur3 = l3;
            first = 0;
            if (debug == 1) printf("tmp->val = %d\n", tmp->val);
        } else {
            cur3->next = tmp;
            cur3 = cur3->next;
            if (debug == 1) printf("tmp->val = %d\n", tmp->val);
        }
        if (debug == 1) printf("v1 = %d, v2 = %d, v3 = %d\n", v1, v2, v3);
        if (cur1 != NULL) cur1 = cur1->next;
        if (cur2 != NULL) cur2 = cur2->next;
    }

    if (carry == 1) {
        tmp = malloc(sizeof(struct ListNode));
        tmp->val = 1;
        tmp->next = NULL;
        cur3->next = tmp;
        carry = 0;
    }

    return l3;
}

int main() {
    struct ListNode* l1 = malloc(sizeof(struct ListNode));
    struct ListNode* l2 = malloc(sizeof(struct ListNode));
    struct ListNode* l3 = malloc(sizeof(struct ListNode));
    struct ListNode* tmp1 = malloc(sizeof(struct ListNode));
    struct ListNode* tmp2 = malloc(sizeof(struct ListNode));
    struct ListNode* tmp3 = malloc(sizeof(struct ListNode));

    // tmp3->val = 3;
    // tmp3->next = NULL;
    // tmp2->val = 4;
    // tmp2->next = tmp3;
    // tmp1->val = 2;
    // tmp1->next = tmp2;
    tmp2->val = 8;
    tmp2->next = NULL;
    tmp1->val = 1;
    tmp1->next = tmp2;
    l1 = tmp1;

    tmp1 = malloc(sizeof(struct ListNode));
    tmp2 = malloc(sizeof(struct ListNode));
    tmp3 = malloc(sizeof(struct ListNode));

    // tmp3->val = 4;
    // tmp3->next = NULL;
    // tmp2->val = 6;
    // tmp2->next = tmp3;
    // tmp1->val = 5;
    // tmp1->next = tmp2;
    tmp1->val = 0;
    tmp1->next = NULL;
    l2 = tmp1;

    l3 = addTwoNumbers(l1, l2);
    printf("%d", l3->val);
    while(l3->next != NULL) {
        l3 = l3->next;
        printf(" -> %d", l3->val);
    }
    printf("\n");
    return 0;
}

 

posted @ 2016-08-05 10:48  兔纸不吃草  阅读(134)  评论(0编辑  收藏  举报