题目将数据以链表方式给出,并且很贴心的设计成了倒序,也就是说我们读取数字的时候正好是按照从地位到高位读取的,因此每次读取是就进行一次计算即可。关于相加时候需要注意的进位问题这里就不多说了。
1 struct ListNode *ans = (struct ListNode *)malloc(sizeof(struct ListNode)); 2 struct ListNode *now = NULL; 3 struct ListNode *next = NULL; 4 int num1 = 0, num2 = 0, sum = 0, flag = 0; 5 now = ans; 6 //now->next = NULL; 7 while (l1 != NULL || l2 != NULL || flag == 1) 8 { 9 num1 = (l1 != NULL) ? l1->val : 0; 10 num2 = (l2 != NULL) ? l2->val : 0; 11 sum = num1 + num2+flag; 12 flag=sum/10; 13 sum=sum%10; 14 15 /*next = (struct ListNode *)malloc(sizeof(struct ListNode)); 16 next->val = sum; 17 now->next = next; 18 next->next = NULL; 19 now = next;*/ 20 21 next=(struct ListNode*)malloc(sizeof(struct ListNode)); 22 next->val=sum; 23 24 now->next=next; 25 next->next=NULL;//这句话特别重要,如果不在末尾设置空指针的话,会报错。 26 now=next; 27 28 l1 = (l1 != NULL) ? l1->next : l1; 29 l2 = (l2 != NULL) ? l2->next : l2; 30 } 31 32 return ans->next;