You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.题目的意思是,输入两个ListNode l1和l2,每个ListNode表明一个‘反序’数字。例如4->3->2表明的是234。咱们的目的是求出两个数字的加和,并以一样的ListNode形式返回。假设每一个listnode都不会存在在首位的0,除非数字自己就是0.node
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.git
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode p = l1; ListNode q = l2; ListNode head = new ListNode(0); ListNode curr = head; int sum =0; while(p != null || q != null){ sum = sum / 10; if(p != null){ sum += p.val; p = p.next; } if(q != null){ sum += q.val; q = q.next; } curr.next = new ListNode(sum % 10); curr = curr.next; } if(sum >= 10){ curr.next = new ListNode(1); } return head.next; }