Java concise solution.


  • 25
    C
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        ListNode p, dummy = new ListNode(0);
        p = dummy;
        while (l1 != null || l2 != null || carry != 0) {
            if (l1 != null) {
                carry += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                carry += l2.val;
                l2 = l2.next;
            }
            p.next = new ListNode(carry%10);
            carry /= 10;
            p = p.next;
        }
        return dummy.next;
    }

  • 1
    P

    Hi there.
    I do not understand what is ListNode in your program. Is it a class you created? Can it be a return type of the method? How can you do l1.val and l1.next? New to Java so please bear with me. Thanks!


  • 0
    J

    @pricool
    ListNode class is pre defined in the question, go back to the question and check the blue part code.
    You can find .next and .val field there.


  • 0
    P

    Thank you very much. Checked it.


  • 0
    A
    This post is deleted!

  • 0
    M

    Hi, I am confused why here we need to define both p and dummy since they are the same? In other words, why can't we just have
    ListNode p = new ListNode(0);
    and at the end, return p.next?

    Thanks in advance!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.