标签:
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 /** 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 }
标签:
原文地址:http://www.cnblogs.com/chess/p/4703540.html