Share my very simple Java solution


  • 3
    K
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry=0;
        ListNode head=new ListNode(0);
        ListNode last=head;
        while (l1!=null ||l2!=null||carry!=0){
            carry+=(l1==null?0:l1.val)+(l2==null?0:l2.val);
            last.next=new ListNode(carry%10);
            carry/=10;
            last=last.next;
            l1=(l1==null?null:l1.next); l2=(l2==null?null:l2.next);
        }
        return head.next;
    }

  • 0
    A

    I would like to know why the "head" stores the list from "last". Every time you update the value "last", will it influence the list "head"?


  • 0
    K

    Hello, "head" pointer is nothing but a reference to the head of the new created list. The program uses "last" pointer to add new item to the end of the list, meanwhile, "head" stays the same, and it always locates the first element of the list. In the end, we return the result list by returning its first element reference (head.next)


Log in to reply
 

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