Java concise solution.

  • 28
    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 =;
            if (l2 != null) {
                carry += l2.val;
                l2 =;
   = new ListNode(carry%10);
            carry /= 10;
            p =;

  • 1

    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 New to Java so please bear with me. Thanks!

  • 0

    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

    Thank you very much. Checked it.

  • 0
    This post is deleted!

  • 0

    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

    Thanks in advance!

  • 2

    @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

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

  • 0

    @caikehe very smart!

Log in to reply

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