Add Two Numbers

C

 1/*Definition for singly-linked list.
 2  struct ListNode {
 3      int val;
 4      struct ListNode *next;
 5  };*/
 6void add_num_to_list(struct ListNode ** res, int num){
 7    printf("%d\n", num);
 8    if(*res == NULL){
 9        (*res) = malloc(sizeof(struct ListNode));
10        (*res)->val = num;
11        (*res)->next = NULL;
12    }
13    else{
14        struct ListNode * temp = *res;
15        while(temp->next != NULL){
16            temp = temp->next;
17        }
18        temp->next = malloc(sizeof(struct ListNode));
19        temp->next->val = num;
20        temp->next->next = NULL;
21    }
22}
23
24struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
25    struct ListNode * temp1 = l1;
26    struct ListNode * temp2 = l2;
27    struct ListNode * ans = NULL;
28    char * num1 = "";
29    char * num2 = "";
30    int carry = 0;
31    int num;
32    int i = 0;
33    while (temp1 != NULL && temp2 != NULL){
34        num = temp1->val + temp2->val + carry;
35        carry = 0;
36        if (num > 9){
37            num = num % 10;
38            carry = 1;
39            add_num_to_list(&ans, num);
40        }
41        else{
42            add_num_to_list(&ans, num);
43        }
44        temp1 = temp1->next;
45        temp2 = temp2->next;
46    }
47    if(carry == 1 && temp1 == NULL && temp2 == NULL){
48        add_num_to_list(&ans, carry);
49        carry = 0;
50    }
51    while(temp1 != NULL){
52        num = temp1->val + carry;
53        carry = 0;
54          if (num > 9){
55            num = num % 10;
56            carry = 1;
57            add_num_to_list(&ans, num);
58        }
59        else{
60            add_num_to_list(&ans, num);
61        }
62        temp1 = temp1->next;
63    }
64    while(temp2 != NULL){
65        num = temp2->val + carry;
66        carry = 0;
67          if (num > 9){
68            num = num % 10;
69            carry = 1;
70            add_num_to_list(&ans, num);
71        }
72        else{
73            add_num_to_list(&ans, num);
74        }
75        temp2 = temp2->next;
76    }
77     if(carry == 1 && temp1 == NULL && temp2 == NULL){
78        add_num_to_list(&ans, carry);
79        carry = 0;
80    }
81    return ans;
82}