You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路分析:
(1)首先对两个链表从前往后开始遍历,逐位相加(计为res),则遍历中的当前位为:res对10取摸,进位(计为carry)为:res/10;这样的过程持续到当中任意一个链表为空时结束,此时有3种情况:
第一种:l1为空,l2不空;第二种:l2为空,l1不空;第三种:l1,l2都为空;
(2)针对3种情况分别加以处理,此时一定要注意链表移到末尾但进位为1的情况;
(3)边界问题:l1或者l2为空的情况!
代码如下,这次是使用c语言实现:
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 if (l1 == NULL) 10 return l2; 11 if (l2 == NULL) 12 return l1; 13 struct ListNode*p1 = l1, *p2 = l2, *pNew = NULL,*pre=p1; 14 int res, carry = 0; 15 while (p1&&p2) 16 { 17 res = p1->val + p2->val + carry; 18 carry = res / 10; 19 p1->val = res % 10; 20 pre = p1; 21 p1 = p1->next; 22 p2 = p2->next; 23 } 24 if (p2 != NULL) 25 { 26 pre->next = p2; 27 while (p2) 28 { 29 res = (p2->val + carry); 30 p2->val = res % 10; 31 carry = res / 10; 32 pre=p2; 33 p2 = p2->next; 34 if(p2==NULL&&carry==1)//一定要考虑这种进位了的情况 35 { 36 pNew=malloc(sizeof(struct ListNode)); 37 pNew->val=1; 38 pNew->next=NULL; 39 pre->next=pNew; 40 } 41 42 } 43 } 44 else if (p1 != NULL) 45 { 46 while (p1) 47 { 48 res = p1->val + carry; 49 p1->val = res % 10; 50 carry = res / 10; 51 pre=p1; 52 p1 = p1->next; 53 if(p1==NULL&&carry==1) 54 { 55 pNew=malloc(sizeof(struct ListNode)); 56 pNew->val=1; 57 pNew->next=NULL; 58 pre->next=pNew; 59 } 60 } 61 } 62 else 63 { 64 if (carry == 1) 65 { 66 pNew =malloc(sizeof(struct ListNode)); 67 pNew->val = carry; 68 pNew->next = NULL; 69 pre->next = pNew; 70 } 71 } 72 return l1; 73 74 }