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
/**
* Definition for singly-linked list.
* Public class ListNode {
* public int val;
* Public ListNode Next;
* Public ListNode (int x) {val = x;}
* }
*/
My Submission 1:accepted Runtime:234ms
1 PublicListNode addtwonumbers (listnode L1, ListNode L2) {2ListNode result=NewListNode (0);3 intCArray =0;4ListNode p =L1;5ListNode q =L2;6ListNode loop =result;7 while(P! =NULL|| Q! =NULL)8 {9 intA = P! =NULL? P.val:0;Ten intb = q! =NULL? Q.val:0; One A intsum = (A + B + carray)%Ten; - - //loop.val = sum; the //loop = Loop.next = new ListNode (0); -Loop.next =Newlistnode (sum); -loop =Loop.next; - +CArray = (A + B + carray)/Ten; -p = p!=NULL? P.next:NULL; +Q = q!=NULL? Q.next:NULL; A at } - if(carray>0) -loop.next=NewListNode (CArray); - returnResult.next; -}View Code
My Submission 2:accepted Runtime:209ms
1 PublicListNode addtwonumbers (listnode L1, ListNode L2) {2ListNode result=NewListNode (0);3 intCArray =0;4ListNode p =L1;5ListNode q =L2;6ListNode loop =result;7 while(P! =NULL|| Q! =NULL)8 {9 intA = P! =NULL? P.val:0;Ten intb = q! =NULL? Q.val:0; One A intsum = a + B +CArray; - - //loop.val = sum; the //loop = Loop.next = new ListNode (0); -Loop.next =NewListNode (sum%Ten); -loop =Loop.next; - +CArray = SUM/Ten; -p = p!=NULL? P.next:NULL; +Q = q!=NULL? Q.next:NULL; A at } - if(carray>0) -loop.next=NewListNode (CArray); - returnResult.next; -}View Code
2. Add Numbers