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
The AC code is as follows:
listnode* Add (listnode* L1, listnode* L2,intLen1,intlen2) { if(Len1 <len2)returnAdd (L2,L1,LEN2,LEN1); //len1>=len2;listnode* tmp1=L1; ListNode* tmp2=L2; intjin=0; while(tmp2!=NULL) { intnow = (Tmp1->val+tmp2->val) +Jin; if(now>=Ten) {Jin= now/Ten; now= now-Ten; } Else{Jin=0; } TMP1->val =Now ; TMP1=tmp1->Next; TMP2=tmp2->Next; } for(;jin>0,tmp1!=null;tmp1=tmp1->next) { intnow = Jin + tmp1->Val; if(Now >=Ten) {Jin= now/Ten; now= now-Ten; } Else{Jin=0; } TMP1->val =Now ; } if(tmp1==null&&jin>0) { //listnode node (jin);listnode* nodenew =NewListNode (Jin); ListNode*tmp=L1; for(;tmp->next!=null;tmp=tmp->next); TMP->next =nodenew; } returnL1;} ListNode* AddTwoNumbers (listnode* L1, listnode*L2) { if(L1 = = NULL && L2 = =NULL)returnNULL; Else if(L1 = =NULL)returnL2; Else if(L2 = =NULL)returnL1; Else { intlen1=0, len2=0; ListNode*tmp; for(tmp=l1;tmp!=null;tmp=tmp->next) {Len1++; } for(tmp=l2;tmp!=null;tmp=tmp->next) {Len2++; } returnAdd (L1,L2,LEN1,LEN2); }}
Others write, also similar. The main thing to consider is rounding. There are a number of situations. When the two linked lists are of equal length, they are placed directly behind as long as the final carry. If not, add a small length to a larger number, and then judge the rounding.
Leetcode "2" ADD numbers