Solution:
classSolution { PublicListNode addtwonumbers (listnode L1, ListNode L2) {ListNode L3=NULL; BooleanAdd =false; while(L1! =NULL|| L2! =NULL) { //number of bits added intPlus; if(L1 = =NULL) {plus=L2.val; } Else if(L2 = =NULL) {plus=L1.val; } Else{plus= L1.val +L2.val; } if(add) {plus++; Add=false; } //Build NodeListNode temp; if(Plus >= 10) {Temp=NewListNode (plus% 10); Add=true; } Else{Temp=NewListNode (plus); } //splicing NodesListNode L3head =L3; if(L3 = =NULL) {L3=temp; if(add && (L1 = =NULL|| L1.next = =NULL) && (L2 = =NULL|| L2.next = =NULL) ) {L3.next=NewListNode (1); } } Else { while(L3head.next! =NULL) {L3head=L3head.next; } L3head.next=temp; if(add && (L1 = =NULL|| L1.next = =NULL) && (L2 = =NULL|| L2.next = =NULL) ) {L3Head.next.next=NewListNode (1); } } //jump to the next one if(L1 = =NULL) {L2=L2.next; } Else if(L2 = =NULL) {L1=L1.next; } Else{L1=L1.next; L2=L2.next; } } returnL3; }}
At the beginning there are three ways of thinking:
- When the converted value is added, it is converted into a linked list, but the values are too large and a long is not sufficient to store
- Flips the list to add, but it is easier to add the rounding before it is flipped
- Adding and rounding directly using linked lists
Finally, the last thought was adopted.
GitHub Address: Https://github.com/CyanChan/Leetcode-Record
Leetcode 2. Add Numbers (Java)