1、题目描述
2、分析
首先将链表翻转,然后做加法。
最后将结果链表翻转。
3、代码
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* L1 = reverseList( l1 );
ListNode* L2 = reverseList( l2 ); ListNode* head = new ListNode( );
ListNode* result = head;
ListNode* p1 = L1;
ListNode* p2 = L2;
int up = ;
while( p1 != NULL && p2 != NULL )
{
if( p1->val + p2->val + up < )
{
result->next = new ListNode( p1->val + p2->val + up );
up = ;
}else{
result->next = new ListNode( p1->val + p2->val + up - );
up = ;
}
p1 = p1->next;
p2 = p2->next;
result = result->next;
} while( p1 != NULL )
{
if( p1->val + up < )
{
result->next = new ListNode( p1->val + up );
up = ;
}
else
{
result->next = new ListNode( p1->val + up - );
up = ;
}
p1 = p1->next;
result = result->next;
} while( p2 != NULL )
{
if( p2->val + up < )
{
result->next = new ListNode( p2->val + up );
up = ;
}
else
{
result->next = new ListNode( p2->val + up - );
up = ;
}
p2 = p2->next;
result = result ->next;
} if( up == )
{
result->next = new ListNode();
result = result->next;
}
ListNode* re = reverseList( head->next ) ;
return re; } ListNode* reverseList(ListNode* l)
{
ListNode* p1 = l;
ListNode* p2 = l->next;
while( p2 != NULL )
{
ListNode* tmp = p2->next;
p2 ->next = p1;
p1 = p2;
p2 = tmp;
} l->next = NULL ;
return p1;
}