title :
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
Code :
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* AddTwoNumbers (listnode* L1, listnode*L2) {ListNode Dummy (-1); ListNode*p = &DUMMY,*P1 = L1,*P2 =L2; intcarry =0; while(P1!=null | | p2!=NULL) { Const intV1 = p1==null?0:p 1->val, v2 = p2==null?0:p 2->val, V = (v1+v2+carry)%Ten; Carry= (V1+v2+carry)/Ten; P->next =NewListNode (v); P= p->Next; P1= P1==null? Null:p1->Next; P2= P2==null? Null:p2->Next; } if(Carry >0) P->next =NewListNode (carry); returnDummy.next; }};
Tips:
The core is to judge the while stop condition: until L1 and L2 are all gone before exiting; if L1 or L2 is finished first, then the bit is 0.
The benefit of the idea above is that you can simplify the code.
"Add-Numbers"