解法:比较简单,用plus表示进位
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 12 ListNode *result=NULL; 13 ListNode *p=NULL; 14 int plus=0; 15 16 while(l1!=NULL && l2!=NULL) 17 { 18 int tmp=l1->val+l2->val+plus; 19 plus=tmp/10; 20 21 if(result == NULL) 22 { 23 result = new ListNode(tmp%10); 24 p = result; 25 } 26 else 27 { 28 p->next = new ListNode(tmp%10); 29 p = p->next; 30 } 31 l1=l1->next; 32 l2=l2->next; 33 } 34 35 36 while(l1!=NULL) 37 { 38 int tmp = l1->val + plus; 39 plus = tmp/10; 40 41 if(result == NULL) 42 { 43 result = new ListNode(tmp%10); 44 p = result; 45 } 46 else 47 { 48 p->next=new ListNode(tmp%10); 49 p=p->next; 50 } 51 l1=l1->next; 52 } 53 54 while(l2!=NULL) 55 { 56 int tmp = l2->val + plus; 57 plus = tmp/10; 58 59 if(result == NULL) 60 { 61 result = new ListNode(tmp%10); 62 p = result; 63 } 64 else 65 { 66 p->next=new ListNode(tmp%10); 67 p=p->next; 68 } 69 l2=l2->next; 70 } 71 72 if(plus!=0) 73 { 74 p->next=new ListNode(plus); 75 } 76 77 return result; 78 } 79 };
LeetCode : add two numbers,布布扣,bubuko.com
原文:http://www.cnblogs.com/crystal-miao/p/3873883.html