输入:[2,4,3] [5,6,4]
输出:[7,0,8]
过程:342+456=807 7->0->8
解法:无非就是两个链表相加,生成新链表而已,只要遍历链表按照十进制加法运算就行了,注意一下进位保存到一下节点。
代码:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* head = NULL;
ListNode* node = NULL;
ListNode* tail = NULL;
ListNode *t1 = l1;
ListNode *t2 = l2;
int jinwei = 0;
int sum;
for (; t1 || t2 || jinwei; )
{
int num1 = 0;
if (t1)
{
num1 = t1->val;
t1 = t1->next;
}
int num2 = 0;
if (t2)
{
num2 = t2->val;
t2 = t2->next;
}
sum = num1 + num2 + jinwei;
if (sum >= 10) {
sum -= 10;
jinwei = 1;
}
else
jinwei = 0;
//尾插法
node = (ListNode*)malloc(sizeof(ListNode));
node->val = sum;
node->next = NULL;
if (head == NULL)
{
head = node;
tail = node;
}
else
{
tail->next = node;
tail = node;
}
}
return head;
}