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
Subscribe to see which companies asked this question
Hide TagsLinked List MathHide Similar Problems(M) Multiply Strings (E) Add Binary
/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {* val = x; * next = NULL; *} *}*/ Public classSolution { PublicListNode addtwonumbers (listnode L1, ListNode L2) {if(L1 = =NULL&& L2 = =NULL) return NULL; if(L2 = =NULL) returnL1; if(L1 = =NULL) returnL2; intPrevious = 0; intsum = l1.val+L2.val; Previous= SUM/10; ListNode R=NewListNode (sum%10); ListNode RC=R; L1=L1.next; L2=L2.next; while(L1! =NULL&& L2! =NULL) {sum= L1.val+l2.val +previous; Previous= SUM/10; R.next=NewListNode (sum%10); R=R.next; L1=L1.next; L2=L2.next; } while(L1! =NULL) {sum= L1.val +previous; Previous= SUM/10; R.next=NewListNode (sum%10); R=R.next; L1=L1.next; } while(L2! =NULL) {sum= L2.val +previous; Previous= SUM/10; R.next=NewListNode (sum%10); R=R.next; L2=L2.next; } if(Previous! = 0) R.next=NewListNode (1); returnRC; }}
2. Add the Numbers