You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 81 public class Solution { 2 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 3 ListNode head = new ListNode(-1); 4 ListNode pre = head; 5 ListNode p1 = l1; 6 ListNode p2=l2; 7 int carry = 0; 8 while(p1!=null&&p2!=null){ 9 int sum = p1.val+p2.val+carry;10 carry = sum/10;11 sum = sum%10;12 pre.next = new ListNode(sum);13 pre =pre.next; 14 p1 = p1.next; 15 p2=p2.next;16 }17 while(p1!=null){18 int sum = p1.val+carry;19 carry = sum/10;20 sum = sum%10;21 pre.next = new ListNode(sum);22 p1= p1.next;23 pre = pre.next;24 }25 while(p2!=null){26 int sum = p2.val+carry;27 carry = sum/10;28 sum = sum%10;29 pre.next = new ListNode(sum);30 p2 = p2.next;31 pre = pre.next;32 }33 if(carry>0){34 pre.next = new ListNode(carry);35 }36 return head.next;37 }38 }