7 question: ADD-Numbers difficulty-medium
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
Answer:
Objective: To make an adder with carry (243+564 = 708)
The main point to consider is – two list of unequal cases and final rounding
Class Solution { Public: ListNode*AddTwoNumbers (ListNode*L1, ListNode*L2) {if(L1== NULL ||L2== NULL)returnL1== NULL ?L2:L1; ListNode Dummy (-1);//Virtual node, pointing to the list headerListNode*L= &Dummy int Carry= 0; int V1, v2,sum; while(L1||L2) {if(L1) {V1=L1 -Val L1=L1 -Next }Else{V1= 0; }if(L2) {v2=L2 -Val L2=L2 -Next }Else{v2= 0; }sum =V1+V2+Carry L -Next= NewListNode (sum % Ten);//post-interpolation, if it is C, write a post-interpolation functionCarry= sum / Ten; L=L -Next }when the//L1,L2 all reach the tail, the final carry is processed if(Carry) {L -Next= NewListNode (carry); }returnDummy.Next }};
Leetcode 5. Two linked list elements add two Numbers