Title Description: Add Numbers
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
Precautions:
1. (2, 4, 3), 2 is the lowest, 3 is the highest bit;
2. The length of the two list is not the same;
3. Carry, (9, 9) + (1) = (0, 0, 1);
4. Do not consider the case of negative numbers.
The idea of knot problem:
1. Define a ListNode to store the results (result);
2. The same bit is added, the digit of the calculated result is passed to result, and the carry is passed to carry. The pointer moves back, and if it is not null, it loops;
3. Finally again judge carry carry;
4. Return the results.
The code is as follows (refer to online):
/** 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) { intcarry =0;//Rounding Flaglistnode* result =NewListNode (0); ListNode* ptr =result; while(L1! = NULL | | L2! =NULL) { intVal1 =0; if(L1! =NULL) {Val1= l1->Val; L1= l1->Next; } intVal2 =0; if(L2! =NULL) {Val2= l2->Val; L2= l2->Next; } intTMP = val1 + Val2 +carry; PTR->next =NewListNode (tmp%Ten); Carry= tmp/Ten; PTR= ptr->Next; } if(Carry = =1) {ptr->next =NewListNode (1); } returnResult->Next; }};
/** 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* Dummyhead =NewListNode (0); ListNode* p =L1; ListNode* Q =L2; ListNode* Curr =Dummyhead; intcarry =0; while(P! = NULL | | Q! =NULL) { intx = (P! = NULL)? P->val:0; inty = (q! = NULL)? Q->val:0; intDigit = carry + x +y; Carry= Digit/Ten; Curr->next =NewListNode (digit%Ten); Curr= curr->Next; if(P! = NULL) p = p->Next; if(q! = NULL) Q = q->Next; } if(Carry >0) Curr->next =NewListNode (carry); returnDummyhead->Next; }};
Leetcode 002 Add-Numbers