给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { 9 10 int num1 = 0; 11 int num2 = 0; 12 int high_res = 0; 13 struct ListNode *tail = NULL; /*尾指针*/ 14 struct ListNode *head = NULL;/*头指针*/ 15 int is_head = 1; 16 17 while(l1 != NULL || l2 != NULL || low_res != 0){ 18 if(l1){ 19 num1 = l1->val; 20 l1 = l1->next; 21 } 22 23 if(l2){ 24 num2 = l2->val; 25 l2= l2->next; 26 } 27 28 struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode)); 29 node->next = NULL; 30 31 /*获取高位数*/ 32 node->val = (num1+num2+high_res)%10; 33 if(is_head){ 34 head = node; 35 tail = node; 36 is_head = 0; 37 }else{ 38 tail->next = node; 39 tail = tail->next; 40 41 } 42 /*获取高位数*/ 43 high_res = (num1+num2+low_res)/10; 44 num1 = 0; 45 num2= 0; 46 47 } 48 49 return head; 50 51 }