Java concise solution.


  • 28
    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!


  • 2
    A

    @mr618show Because p will be used to store current digit in loop and the object address stored in p will change. Use dummy to stay at the beginning to identify the head place.


  • 0
    A

    @caikehe This is hilarious! I just answered this question and my answer is almost identical to yours, even down to the naming! GMTA :)


  • 0
    H

    @caikehe very smart!


Log in to reply
 

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