Title Source: https://leetcode.com/problems/add-two-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
Title: Give two linked lists L1 and L2, add the corresponding elements, if the resulting carry is reserved bit, the corresponding 10 bits are added to the corresponding elements.
The idea of disintegration:
First determine whether the linked list is empty, if L1 empty, return L2 directly, instead return L2
Then find the L1 and L2 list of the shortest length of a min_len, into the loop
During the cycle, in order to reduce the cost of space, the linked list L1 can be used as the final result linked list, only need to change the L1 maximum capacity of l1+l2, and the addition process requires an integer TEMP variable to hold the carry.
After the loop is over, determine whether L1 or L2 is empty (you can mark the shortest linked list before), and then put all other elements of the non-empty list in the result list.
Submit Code:
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 Ten classSolution { One Public: AListNode *addtwonumbers (ListNode *l1, ListNode *L2) { - //Start Typing your/C + + solution below - //Do not write int main () function the //ListNode *presult = NULL; - //ListNode **pcur = &pResult; - -ListNode RootNode (0); +ListNode *pcurnode = &RootNode; - intA =0; + while(L1 | |L2) A { at intV1 = (L1? L1->val:0); - intV2 = (L2? L2->val:0); - inttemp = v1 + v2 +A; -A = temp/Ten; -ListNode *pnode =NewListNode ((temp%Ten)); -Pcurnode->next =Pnode; inPcurnode =Pnode; - if(L1) toL1 = l1->Next; + if(L2) -L2 = l2->Next; the } * if(A >0) $ {Panax NotoginsengListNode *pnode =NewListNode (a); -Pcurnode->next =Pnode; the } + returnRootnode.next; A } the};
The following code for the array of solutions, the same process, but the data storage structure is different:
1#include <bits/stdc++.h>2 #defineMAX 10000103 4 using namespacestd;5 6 intMain ()7 {8 intn1,n2;9 while(~SCANF ("%d%d",&n1,&n2))Ten { One int*a=New int[n1+n2+1]; A int*b=New int[N2]; - for(intI=0; i<n1;i++) -scanf"%d",&a[i]); the for(intI=0; i<n2;i++) -scanf"%d",&b[i]); - intminlen=min (n1,n2); - intmaxlen=n1+n2-Minlen; + inttemp=0; - for(intI=0; i<minlen;i++) + { Aa[i]=a[i]+b[i]+temp; at if(a[i]>=Ten) - { -temp=a[i]/Ten; -a[i]=a[i]%Ten; - } - } in for(intj=minlen;j<maxlen;j++) - { to if(maxlen==N1) +a[j]=A[j]; - Else thea[j]=B[j]; * } $ for(intI=0; i<maxlen;i++)Panax Notoginsengprintf"%d", A[i]); -printf"\ n"); the } +}
Leetcode 2 Add Numbers (linked list operation)