Test instructions
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
Analysis:
List operation problem, the algorithm is not complex, pay attention to the language is not a problem on the line, followed by the wording to be as concise as possible, his first kind of writing is very lengthy, improved to get method 2.
List Note: Empty table judgment, dummy node application, etc.
Code Listing 1:
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 classSolution {Ten Public: Onelistnode* addtwonumbers (listnode* L1, listnode*L2) { A if(L1 = =nullptr) { - return< - } the if(L2 = =nullptr) { - returnL1; - } -ListNode Dummy (0); +listnode*result; -Dummy.next =result; +result = &dummy; A intcarry =0; at while(L1! = nullptr && L2! =nullptr) { -listnode* NewNode =NewListNode (0); -Result-Next =NewNode; - inttemp = L1 val + L2 Val +carry; - if(Temp >=Ten){ -carry =1; inNewNode, val = temp-Ten; - } to Else{ +carry =0; -NewNode, val =temp; the } *L1 = L1Next; $L2 = L2Next;Panax Notoginsengresult =NewNode; - } the + if(L1! =nullptr) { A while(L1! =nullptr) { thelistnode* NewNode =NewListNode (0); + //there is still a possibility of rounding! - inttemp = carry + L1Val; $ if(Temp >=Ten){ $carry =1; -NewNode, val = temp-Ten; - } the Else{ -carry =0;WuyiNewNode, val =temp; the } -Result-Next =NewNode; Wuresult =NewNode; -L1 = L1Next; About } $ } - if(L2! =nullptr) { - while(L2! =nullptr) { -listnode* NewNode =NewListNode (0); A inttemp = carry + L2Val; + if(Temp >=Ten){ thecarry =1; -NewNode, val = temp-Ten; $ } the Else{ thecarry =0; theNewNode, val =temp; the } -Result-Next =NewNode; inresult =NewNode; theL2 = L2Next; the } About } the if(Carry = =1){ thelistnode* NewNode =NewListNode (0); theNewNode, val =1; +Result-Next =NewNode; - } the returnDummy.next;Bayi } the};
Various conditions are too cumbersome to determine, the code is smelly and long ...
After the improvement , the L1,l2,carry judgment is processed together, and the/and% are substituted for the IF statement to get the code 2.
Code Listing 2:
1 classSolution {2 Public:3listnode* addtwonumbers (listnode* L1, listnode*L2) {4ListNode Dummy (0);5listnode* result = &dummy;6 intcarry =0;7 while(L1! = nullptr | | L2! = NULLPTR | | carry =1 ) {8Result-Next =NewListNode (0);9result = ResultNext;Ten intTempVal =0; One if(L1! =nullptr) { ATempVal + = L1Val; -L1 = L1Next; - } the if(L2! =nullptr) { -TempVal + = L2Val; -L2 = L2Next; - } + if(Carry = =1) { -tempval++; + } A //without the If Judgment atresult, val = tempval%Ten; -carry = tempval/Ten; - } - returnDummy.next; - } -};
Leetcode2 ADD Numbers