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
Problem Solving Ideas:
Defines three listnode L1, L2,result, where result is the output of the return statement, L1, L2 is an incoming parameter.
Assign the L1 to result, execute result.val+=l2.val, and then L1 as the pointer level down until L2.NEXT is null. Of course, there will be a lot of boundary conditions, self-debug a bit better.
The Java code is as follows:
public class Solution { static public ListNode addtwonumbers (listnode L1, ListNode L2) { ListNode result=l1; while (true) { l1.val+=l2.val; if (l1.val>=10) { l1.val%=10; if (l1.next==null) l1.next=new ListNode (1); else l1.next.val+=1; } if (l2.next==null) {ListNode L3=l1.next;while (true) {if (l3==null) break;if (l3.val==10) {l3.val%=10; if (l3.next==null) l3.next=new ListNode (1); else l3.next.val+=1;} L3=l3.next;} break;} L2=l2.next; if (l1.next==null) { l1.next=new listnode (0); } L1=l1.next; } return result;} }
Java for Leetcode 002 Add-Numbers