1、题目描述
2、分析
首先将链表翻转,然后做加法。
最后将结果链表翻转。
3、代码
1 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 2 3 ListNode* L1 = reverseList( l1 ); 4 ListNode* L2 = reverseList( l2 ); 5 6 ListNode* head = new ListNode( 0 ); 7 ListNode* result = head; 8 ListNode* p1 = L1; 9 ListNode* p2 = L2; 10 int up = 0; 11 while( p1 != NULL && p2 != NULL ) 12 { 13 if( p1->val + p2->val + up < 10 ) 14 { 15 result->next = new ListNode( p1->val + p2->val + up ); 16 up = 0; 17 }else{ 18 result->next = new ListNode( p1->val + p2->val + up - 10 ); 19 up = 1; 20 } 21 p1 = p1->next; 22 p2 = p2->next; 23 result = result->next; 24 } 25 26 while( p1 != NULL ) 27 { 28 if( p1->val + up < 10 ) 29 { 30 result->next = new ListNode( p1->val + up ); 31 up = 0; 32 } 33 else 34 { 35 result->next = new ListNode( p1->val + up - 10 ); 36 up = 1; 37 } 38 p1 = p1->next; 39 result = result->next; 40 } 41 42 while( p2 != NULL ) 43 { 44 if( p2->val + up < 10 ) 45 { 46 result->next = new ListNode( p2->val + up ); 47 up = 0; 48 } 49 else 50 { 51 result->next = new ListNode( p2->val + up - 10 ); 52 up = 1; 53 } 54 p2 = p2->next; 55 result = result ->next; 56 } 57 58 if( up == 1 ) 59 { 60 result->next = new ListNode(1); 61 result = result->next; 62 } 63 ListNode* re = reverseList( head->next ) ; 64 return re; 65 66 } 67 68 ListNode* reverseList(ListNode* l) 69 { 70 ListNode* p1 = l; 71 ListNode* p2 = l->next; 72 while( p2 != NULL ) 73 { 74 ListNode* tmp = p2->next; 75 p2 ->next = p1; 76 p1 = p2; 77 p2 = tmp; 78 } 79 80 l->next = NULL ; 81 return p1; 82 }