Title: Leetcode 002 Add-Numbers
Test instructions: Given two linked lists that represent non-negative numbers, which are stored in reverse order, each node contains a separate number that adds the two numbers and returns a new linked list.
Examples:
Input: (2, 4, 3) + (5, 6, 4)
Output: 7-> 0-8
The structure of each node of the list:
1 struct ListNode {2 int Val; 3 ListNode *Next; 4 ListNode (int x): Val (x), Next (NULL) {}5 };
Ideas:
Add to the bitwise, consider rounding.
Learn how to generate a linked list:
1 New ListNode (0), *ptr = ans; 2 New ListNode (val); 3 t = t->next; 4 return ans->next;
Code Listing 1: Using arrays
Because it is unfamiliar to the list, try to convert the linked list to an array, then get the result and then reassign it to the linked list. But creating a linked list refers to someone else's code: the first node of the list is just used to pass pointers.
1 classSolution {2 Public:3listnode* addtwonumbers (ListNode *l1, ListNode *L2) {4 inta[20000], b[20000], NA =0, NB =0;5Memset (A,0,sizeof(a));6memset (b,0,sizeof(b));7 while(L1)8 {9a[na++] = l1->Val;TenL1 = l1->Next; One } A while(L2) - { -b[nb++] = l2->Val; theL2 = l2->Next; - } -Na =Max (Na, NB); - for(inti =0; I < na | | I < NB; i++) + { -A[i] + =B[i]; +a[i+1] + = a[i]/Ten; AA[i]%=Ten; at } - if(A[na]) na++; - -ListNode *ans =NewListNode (0); -L1 =ans; - for(inti =0; i < na; i++) in { -L1->next =NewListNode (A[i]); toL1 = l1->Next; + } - returnAns->Next; the } *};
Use the linked list to do directly, to consider that if the two linked list is not the same length, there will be access to the list of a node of the Val is empty, so the situation to be processed. In addition, in other people's code to see someone said, if one of the list is short, access to the end of the time can be another long link to the back of the linked list, but there is a counter example:
Input: (0, 1) + (9-> 9, 9–> 9) or more than 9, the case of continuous rounding is required.
1 classSolution {2 Public:3listnode* addtwonumbers (listnode* L1, listnode*L2) {4 intFlag =0;5listnode* ans =NewListNode (0);6listnode* T =ans;7 8 while(L1! = NULL | | L2! =NULL)9 {Ten intVal; One if(!L1) A { - if(Flag = =0) - { theT->next =L2; - Break; - } -val = l2->val +Flag; +L2 = l2->Next; - } + A Else if(!L2) at { - if(Flag = =0) - { -T->next =L1; - Break; - } inval = l1->val +Flag; -L1 = l1->Next; to } + - Else the { *val = l1->val + L2->val +Flag; $L1 = l1->Next;Panax NotoginsengL2 = l2->Next; - } theFlag = val/Ten; +Val%=Ten; AT->next =NewListNode (val); thet = t->Next; + } - $ if(flag) T->next =NewListNode (1); $ returnAns->Next; - } -};
"Leetcode" 002 Add-Numbers