1、题目描述
2、题目描述
题目思路可以参考合并单链表的思路,定义一个全局 进位标志,如果两个数值相加得到需要进位,则将进位标志置为1 。
3、代码
1 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 2 3 ListNode* head = new ListNode( 0 ) ; 4 ListNode* result = head; 5 ListNode* p1 = l1; 6 ListNode* p2 = l2; 7 int up = 0; 8 while( p1 != NULL && p2 != NULL ) 9 { 10 int r = p1->val + p2->val ; 11 r += up; 12 if( r < 10 ) 13 { 14 result->next = new ListNode( r ) ; 15 up = 0; 16 } 17 else 18 { 19 result -> next = new ListNode( r -10) ; 20 up = 1; 21 } 22 p1 = p1->next; 23 p2 = p2->next; 24 result = result ->next; 25 } 26 27 28 29 while( p1 != NULL ) 30 { 31 if( p1->val + up < 10 ) 32 { 33 result->next = new ListNode( p1->val + up ); 34 up = 0; 35 }else{ 36 result->next = new ListNode( p1->val + up - 10 ); 37 up = 1; 38 } 39 p1 = p1->next; 40 result = result ->next; 41 } 42 43 while( p2 != NULL ) 44 { 45 if(p2->val + up < 10) 46 { 47 result->next = new ListNode( p2->val + up); 48 up = 0; 49 } 50 else 51 { 52 result->next = new ListNode( p2->val + up - 10 ) ; 53 up = 1; 54 } 55 p2 = p2->next; 56 result = result->next; 57 } 58 59 if( up != 0 && p1 == NULL && p2 == NULL ) 60 { 61 result->next = new ListNode(up) ; 62 } 63 return head->next; 64 65 }