Test instructions: the addition of large number of linked list, but the number on the list is reversed.
Source: https://leetcode.com/problems/add-two-numbers/
Analysis:
1. If the linked list is empty, no calculation is necessary; If all two linked lists are empty, the return is empty (the list is not cooked).
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==null)returnL2; - if(L2==null)returnL1; - the intcarry =0; -listnode* tail =NewListNode (0); -listnode* ptr =tail; - + while(L1! = NULL | | L2! =NULL) { - intVal1 =0; + if(L1! =NULL) { AVal1 = l1->Val; atL1 = l1->Next; - } - - intVal2 =0; - if(L2! =NULL) { -Val2 = l2->Val; inL2 = l2->Next; - } to + intTMP = val1 + Val2 +carry; -Ptr->next =NewListNode (tmp%Ten); thecarry = tmp/Ten; *PTR = ptr->Next; $ }Panax Notoginseng if(Carry = =1) Ptr->next =NewListNode (1); - returnTail->Next; the } +};
[Leetcode] ADD Numbers