问题描述:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
示例:Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
以下是问题分析:
本题是将两个数按照逆序存放在两个链表里,然后求这两个数的和,同样以逆序的方式输出为链表。此题中可能遇到的陷阱==》变量的生存周期问题(ListNode的某一变量在addTwoNumbers函数内使用,出了该范围无效)。
以下是我按照普通套路些的代码
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){
ListNode* res = l1,*temp;
int flag = 0;
int tempval;
while(l1 != NULL && l2 != NULL){
tempval = l1->val + l2->val + flag;
flag = tempval / 10;
tempval = tempval % 10;
l1->val = tempval;
temp = l1;
l1 = l1->next;
l2 = l2->next;
}
if(l1 == NULL){
temp->next = l2;
l1 = l2;
}
while(l1 != NULL){
tempval = l1->val + flag;
flag = tempval / 10;
tempval = tempval % 10;
l1->val = tempval;
temp = l1;
l1 = l1->next;
}
if(flag){
ListNode * p = (ListNode *)malloc(sizeof(ListNode));
ListNode f(flag);
p->val = f.val;
p->next = f.next;
temp->next = p;
}
return res;
}
欢迎小伙伴们一起探讨~