Title Description:
You are given, linked lists representing, and non-negative numbers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.
Input: (2, 4, 3) + (5, 6, 4)
Output: 7-0–> 8
Program code:
#include <gtest/gtest.h>using namespacestd;structListNode {intVal; ListNode*Next; ListNode (intx): Val (x), Next (NULL) {}}; ListNode* AddTwoNumbers (listnode* L1, listnode*L2) {ListNode* result =0; ListNode* current =0; intcarry =0; while(L1! = NULL | | L2! =NULL) { intValue =0; if(L1! =NULL) {Value+ = L1->Val; L1= l1->Next; } if(L2! =NULL) {Value+ = L2->Val; L2= l2->Next; } if(Current = =NULL) { Current= result =NewListNode (value%Ten); Carry= value/Ten; } Else{ Current->next =NewListNode ((value + carry)%Ten); Carry= (value + carry)/Ten; Current= current->Next; } } if(carry) {if(Current = =NULL) { Current= result =NewListNode (carry); } Else{ Current->next =NewListNode (carry); Current= current->Next; } } returnresult;} TEST (Pratices, taddtwonumbers) {//(2, 4, 3) + (5, 6 , 4) 7, 0, 8listnode* L1 =NewListNode (2); L1->next =NewListNode (4); L1->next->next =NewListNode (3); ListNode* L2 =NewListNode (5); L2->next =NewListNode (6); L2->next->next =NewListNode (4); ListNode* result =addtwonumbers (L1,L2); //NULL + (2, 4, 3)result =addtwonumbers (NULL,L1); //(2, 4, 3) + (5, 6, 4, 4)L2->next->next->next =NewListNode (4); Result=addtwonumbers (L1,L2); //1 + 9->9L1 =NewListNode (1); L2=NewListNode (9); L2->next =NewListNode (9); Result=addtwonumbers (L1,L2);}
[Algorithm Exercise] ADD Numbers