求:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
解:
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){ struct ListNode* resultList = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode* currentNode = resultList; int x,y; int carry = 0; while(l1!=NULL || l2!=NULL){ if(l1==NULL){ x=0; }else{ x=l1->val; l1=l1->next; } if(l2==NULL){ y=0; }else{ y=l2->val; l2=l2->next; } struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode)); newNode->val = x+y+carry; newNode->next = NULL; currentNode->next = newNode; currentNode = newNode; if(newNode->val>=10){ newNode->val-=10; carry = 1; }else{ carry = 0; } } if(carry){ struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode)); newNode->val=1; newNode->next=NULL; currentNode->next = newNode; } return resultList->next; }
来源:oschina
链接:https://my.oschina.net/u/4469818/blog/3191890