2. Add Two Numbers

2. Add Two Numbers

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
     
    ListNode dummyHead = new ListNode(0);
    ListNode p = l1, q = l2, curr = dummyHead;
    int carry = 0;
    while (p != null || q != null) {
     
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    if (carry > 0) {
     
        curr.next = new ListNode(carry);
    }
    return dummyHead.next;
}

我在这里有个疑惑,dummyHead在代码中明明没有用到,为啥最后输出反而是dummyHead.next呢?

我猜测:curr = dummyHead这里可能是双向绑定,于是最后dummyHead.next就是currcurr.next

2. Add Two Numbers_第1张图片

你可能感兴趣的:(leecode,java)