# Leetcode: Add Two Numbers

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if (l1 == NULL){
return l2;
}
if (l2 == NULL){
return l1;
}
ListNode *ans = l1;
int cur = 0;
ListNode *p=l1;
while (l1 && l2){
int temp = l1->val + l2->val + cur;
l1->val = temp % 10;
cur = temp / 10;
p = l1;
l2 = l2->next;
if (l1->next == NULL && l2!=NULL){
l1->next = new ListNode(0);
l1 = l1->next;
break;

}
l1 = l1->next;
}
if (l1 == NULL && l2 == NULL && cur){
ListNode * ff = ans;
while (ff->next != NULL){
ff = ff->next;
}
ff->next = new ListNode(1);

}

else if (l2!=NULL){
while (l2 != NULL){
int temp = cur + l2->val;

l1->val = temp % 10;
cur = temp / 10;
l2 = l2->next;
p = l1;

l1->next = new ListNode(0);
l1 = l1->next;

}
if (cur){
l1->val = 1;
}
}
else if (l1!=NULL)
while(l1 != NULL){

int temp = cur  + l1->val;
l1->val = temp % 10;
cur = temp /= 10;
p = l1;

if (l1->next == NULL &&  cur){
l1->next = new ListNode(cur);
l1->next->val = cur;
l1 = l1->next;
break;

}

l1 = l1->next;

}
//  cout << ans->val << " " << ans->next->val << endl;
//cout << "fuck" << p->val << endl;

if (p->next && p->next->val == 0){
p->next = NULL;
}
return ans;
}
};

• 本文已收录于以下专栏：

## Leetcode: Add Two Numbers (2)

You are given two linked lists representing two non-negative numbers. The digits are stored in orde...

## [leetcode NO.3] Add Two Numbers (JAVA)

You are given two linked lists representing two non-negative numbers. The digits are stored in rever...

leetcode第2和第3题

## LeetCode 2 Add Two Numbers

You are giventwo linked lists representing two non-negative numbers. The digits are storedin reverse...

## 【Leetcode】445. Add Two Numbers II

445. Add Two Numbers II You are given two non-empty linked lists representing two non-negative ...

## LeetCode 445. Add Two Numbers II--两个链表均按照由尾部到头部计算两个结点数值之和，保持进位

You are given two non-empty linked lists representing two non-negative integers. The most significan...

## LeetCode 2. Add Two Numbers

2. Add Two Numbers[Chinese ver]问题：你将获得两个非空 linked lists来表示两个非负整数。 数字以反向的顺序存储，并且它们的每个节点包含一位数字。 将两个数字相...

## leetcode3--Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in rever...

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)