# LeetCode (2)：两数相加

LeetCode 相关的文章：

#### 题目描述

C 语言给出的函数定义如下：

/**

* struct ListNode {

*     int val;

*     struct ListNode *next;

* };

*/

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

}

#### 代码实现

C 语言的代码如下

/**

* struct ListNode {

*     int val;

*     struct ListNode *next;

* };

*/

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

if (l1 == NULL) {

return l2;

}

if (l2 == NULL) {

return l1;

}

struct ListNode* one = l1;

struct ListNode* two = l2;

struct ListNode* sum = NULL;

struct ListNode* tsum = NULL;

/* 进位值 */

int tmp = 0;

struct ListNode* tn = NULL;

while (one != NULL || two != NULL) {

int o = 0, t = 0, s = 0;

if (one != NULL) {

o = one->val;

one = one->next;

}

if (two != NULL) {

t = two->val;

two = two->next;

}

/* 带进位加法 */

s   = o + t + tmp;

tmp = s / 10;

s   = s % 10;

tn = (struct ListNode*)malloc(sizeof(struct ListNode));

tn->val = s;

tn->next = NULL;

if (sum != NULL) {

tsum->next = tn;

tsum = tn;

} else {

sum = tn;

tsum = tn;

}

}

if (tmp != 0) {

tn = (struct ListNode*)malloc(sizeof(struct ListNode));

tn->val = tmp;

tn->next = NULL;

tsum->next = tn;

}

return sum;

}

#### 提交结果

”，然后观察
“输出” 和 “预期结果”

” 按钮。点击 “提交” 按钮后，系统会使用更多的测试用例来测试我们写的函数体，

。我们的代码提交后的截图如下：