普通的循环解法,C代码:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 9 10 struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){ 11 int total = 0, next1 = 0; 12 13 struct ListNode *result = (struct ListNode *)malloc(sizeof(struct ListNode)); 14 struct ListNode *cur = result; 15 cur->next = NULL; 16 17 while(l1 && l2){ 18 total = l1->val + l2->val + next1; 19 cur->next = (struct ListNode *)malloc(sizeof(struct ListNode)); 20 cur->next->val = total % 10; 21 cur->next->next = NULL; 22 next1 = total / 10; 23 l1 = l1->next; 24 l2 = l2->next; 25 cur = cur->next; 26 } 27 28 while(l1){ 29 total = l1->val + next1; 30 cur->next = (struct ListNode *)malloc(sizeof(struct ListNode)); 31 cur->next->val = total % 10; 32 cur->next->next = NULL; 33 next1 = total / 10; 34 l1 = l1->next; 35 cur = cur->next; 36 } 37 38 while(l2){ 39 total = l2->val + next1; 40 cur->next = (struct ListNode *)malloc(sizeof(struct ListNode)); 41 cur->next->val = total % 10; 42 next1 = total / 10; 43 cur->next->next = NULL; 44 l2 = l1->next; 45 cur = cur->next; 46 } 47 48 if(next1 != 0){ 49 cur->next = (struct ListNode *)malloc(sizeof(struct ListNode)); 50 cur->next->val = next1; 51 cur->next->next = NULL; 52 } 53 54 return result->next; 55 56 }View Code
标签:total,ListNode,cur,next,leetcode02,l1,刷题,两数,struct From: https://www.cnblogs.com/yx12789/p/16712587.html