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
Analysis: Add bits-by-bit and consider rounding.
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: OneListNode *addtwonumbers (ListNode *l1, ListNode *L2) { A if(!L1 | |!L2) { - returnNULL; - } the intcarry =0;//Rounding -ListNode * result =NewListNode (0); -ListNode * first = result;//trace the current node of the result list -ListNode * pre = NULL;//trace the previous node of the results list + //When both L1 and L2 do not exceed the node at the end of the list - while(L1 &&L2) { +First->val = (carry + l1->val + l2->val)%Ten; ACarry = (carry + l1->val + l2->val)/Ten; at if(Pre = =NULL) -Pre =First ; - Else { -Pre->next =First ; -Pre =First ; - } inFirst =NewListNode (0); -L1 = l1->Next; toL2 = l2->Next; + } - //When both L1 and L2 are over the node at the end of the list the if(!L1 &&!)L2) { * if(Carry = =1) { $First->val =carry;Panax NotoginsengPre->next =First ; - } the returnresult; + } A //when L1 exceeds the end and L2 is not over the if(!l1 &&L2) { + while(L2) { -First->val = (carry + l2->val)%Ten; $Carry = (carry + l2->val)/Ten; $ if(Pre = =NULL) -Pre =First ; - Else { thePre->next =First ; -Pre =First ;Wuyi } theFirst =NewListNode (0); -L2 = l2->Next; Wu } - if(Carry = =1) { AboutFirst->val =1; $Pre->next =First ; - } - returnresult; - } A //when L2 exceeds the end and L1 is not over + if(!l2 &&L1) { the while(L1) { -First->val = (carry + l1->val)%Ten; $Carry = (carry + l1->val)/Ten; the if(Pre = =NULL) thePre =First ; the Else { thePre->next =First ; -Pre =First ; in } theFirst =NewListNode (0); theL1 = l1->Next; About } the if(Carry = =1) { theFirst->val =1; thePre->next =First ; + } - returnresult; the }Bayi the } the};
Leetcode algorithm 02