Add Two Numbers as Lists

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 -> 8

    342 + 465 = 807

Make sure there are no trailing zeros in the output list
So, 7 -> 0 -> 8 -> 0 is not a valid response even though the value is still 807.

Solution:

Time: O(n)
Space: O(n)

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     public int val;
 *     public ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode A, ListNode B) {
        ListNode dummy = new ListNode(0);
        ListNode p = dummy;
        int carry = 0;
        while (A != null && B != null) {
            ListNode node = new ListNode(0);
            int val = A.val + B.val + carry;
            node.val = val % 10;
            carry = val / 10;
            A = A.next;
            B = B.next;
            p.next = node;
            p = p.next;
        }
        while (A != null) {
            ListNode node = new ListNode(0);
            int val = A.val + carry;
            node.val = val % 10;
            carry = val / 10;
            A = A.next;
            p.next = node;
            p = p.next;
        }
        while (B != null) {
            ListNode node = new ListNode(0);
            int val = B.val + carry;
            node.val = val % 10;
            carry = val / 10;
            B = B.next;
            p.next = node;
            p = p.next;
        } 
        if (carry != 0) {
            p.next = new ListNode(1);
        }
        return dummy.next;
    }
}