给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(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* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{
int remainder = 0;
int integer = 0;
int sum = 0;
int l1_val = 0;
int l2_val = 0;
struct ListNode *l_end = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode *l_head = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode *l_node;
struct ListNode *l1_p = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode *l2_p = (struct ListNode *)malloc(sizeof(struct ListNode));
l1_p = l1;
l2_p = l2;
/*尾插法,当前只有头结点,且为空*/
l_head->next = NULL;
l_end = l_head;
while((l1_p != NULL) || (l2_p != NULL))
{
l1_val = (l1_p != NULL)?l1_p->val:0;
l2_val = (l2_p != NULL)?l2_p->val:0;
sum = l1_val + l2_val + integer;
remainder = sum %10;
l_node = (struct ListNode *)malloc(sizeof(struct ListNode));
l_node->next = NULL;
l_node->val = remainder;
l_end->next = l_node;
l_end = l_node;
if(l1_p != NULL)
{
l1_p = l1_p->next;
}
if(l2_p != NULL)
{
l2_p = l2_p->next;
}
integer = sum /10;
}
if(integer > 0)
{
l_node = (struct ListNode *)malloc(sizeof(struct ListNode));
l_node->next = NULL;
l_node->val = integer;
l_end->next = l_node;
l_end = l_node;
}
return l_head->next;
}