给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 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 *myLinkedListCreate() {
struct ListNode *my_linked_list = (struct ListNode *)malloc(sizeof(struct ListNode ));
my_linked_list->next = NULL;
return my_linked_list;
}
void myLinkedListAddAtTail(struct ListNode * obj, int val) {
struct ListNode *p;
struct ListNode *q = (struct ListNode *)malloc(sizeof(struct ListNode));
p = obj;
while (p->next)
{
p = p->next;
}
p->next = q;
q->val = val;
q->next = NULL;
}
struct ListNode* reverseList(struct ListNode* head){
if (!head || !head->next)
return head;
struct ListNode *p = head;
struct ListNode *q = head;
struct ListNode *new_head = head;
while (q->next)
{
p = q->next;
q->next = q->next->next;
p->next = new_head;
new_head = p;
p = q->next;
}
return new_head;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode *p = l1;
struct ListNode *q = l2;
struct ListNode *add_list = myLinkedListCreate();
struct ListNode *temp = add_list;
struct ListNode *temp_front = add_list;
int flag = 0; //进位标志
temp->next = NULL;
while (p && q)
{
temp->val = (p->val + q->val + flag)%10;
flag = ((p->val + q->val + flag)>=10) ? 1 : 0;
p = p->next;
q = q->next;
myLinkedListAddAtTail(add_list, temp->val);
temp_front = temp;
temp = temp->next;
}
while (p)
{
temp->val = (p->val + flag)%10;
flag = ((p->val + flag)>=10) ? 1 : 0;
p = p->next;
myLinkedListAddAtTail(add_list, temp->val);
temp_front = temp;
temp = temp->next;
}
while (q)
{
temp->val = (q->val + flag)%10;
flag = ((q->val + flag)>=10) ? 1 : 0;
q = q->next;
myLinkedListAddAtTail(add_list, temp->val);
temp_front = temp;
temp = temp->next;
}
if (flag == 1)
{
temp->val = 1;
temp->next = NULL;
}
else if (flag == 0)
{
temp_front->next = NULL;
}
return add_list;
}