# [leetcode题解]02.Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

`Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.`

`输入：(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出：7 -> 0 -> 8 原因：342 + 465 = 807`

```/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
struct ListNode *addOneDigit(struct ListNode *head, int val) {
struct ListNode *node = calloc(1, sizeof(struct ListNode));
node->val = val;
head->next = node;
head = head->next;
return head;
}

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode res;
int c = 0;
int a = 0;
int b = 0;
int sum = 0;
struct ListNode *now = &res;

while (l1 != NULL || l2 != NULL) {
a = 0;
if (l1 != NULL) {
a = l1->val;
l1 = l1->next;
}

b = 0;
if (l2 != NULL) {
b = l2->val;
l2 = l2->next;
}

sum = a + b + c;
c = sum / 10;
sum = sum % 10;

now = addOneDigit(now, sum);
}

if (c != 0)
addOneDigit(now, c);

return res.next;
}```