给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int cf=0,sum;
int val1,val2;
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* current = dummy;
while(l1!=NULL||l2!=NULL||cf!=0){
val1 = (l1!=NULL)?l1->val:0;
val2 = (l2!=NULL)?l2->val:0;
sum = val1+val2+cf;
cf = sum/10;
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = sum%10;
newNode->next = NULL;
current->next = newNode;
current = current->next;
if(l1!=NULL){
l1=l1->next;
}
if(l2!=NULL){
l2=l2->next;
}
}
// struct ListNode* result = dummy->next;
// free(dummy);
return dummy->next;
}