# C Solution

• Using typedef of struct ListNode as Node for brevity.

``````void add_node (Node ** res, Node ** prev, Node * new_node) {
if (*res && *prev)
(*prev)->next = new_node;
else
*res = new_node;
*prev = new_node;
}

int check_carry (node ** res_node, int tmp) {
int carry;

if (tmp >= 10) {
tmp -= 10;
carry = 1;
} else {
carry = 0;
}

(*res_node)->val = tmp;
return carry;
}

int loop_remaining_side (Node ** res, Node ** prev, Node * lr, int carry) {
int tmp;
while (lr) {
Node *res_node = (Node *) calloc (1, sizeof (Node));
tmp = lr->val + carry;
carry = check_carry (&res_node, tmp);

lr = lr->next;
}

return carry;
}

/* Sum two linked lists into one */
Node * add_with_lists (Node * a, Node * b) {
int tmp;
int carry = 0;
node *res = NULL;
node *prev = NULL;

//  add both lists until one finishes
while (a && b) {
Node *res_node = (Node *) calloc (1, sizeof (Node));

tmp = a->val + b->val + carry;
carry = check_carry (&res_node, tmp);

a = a->next;
b = b->next;
}

// one list might be longer than the other, add it to the sum
carry = loop_remaining_side (&res, &prev, a, carry);
carry = loop_remaining_side (&res, &prev, b, carry);

// we might need one more digit (ex, 1 + 99)
if (carry) {
Node *res_node = (Node *) calloc (1, sizeof (Node));
res_node->val = 1;