L2 Add Two Numbers

dummyNode

Problem

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.

Solution

We need a dummyNode so we could get a head for the linked list. Then, we create two node p1 and p2, so we could check the value, just in case if the node is null so we could return 0.

sum equals the carry from last round plus new two nodes.

carry is for the the remainder. cur.next will be the sum more than ten. After the while loop, if we still have remainder, the next node will be the remainder.

Note: 7 % 10 = 7, 11 % 10 = 1

public ListNode addTwoNum(ListNode l1, ListNode l2){
    ListNode dummy = new ListNode(0);
    ListNode p1 = l1, p2 = l2, cur = dummy;
    int carry = 0;
    while(p1 != null || p2 != null){
        int x = (p1 == null) ? 0 : p1.val;
        int y = (p2 == null) ? 0 : p2.val;
        int sum = carry + x + y;
        carry = sum / 10;
        cur.next = new ListNode(sum % 10);
        cur = cur.next;
        if(p1 != null) p1 = p1.next;
        if(p2 != null) p2 = p2.next;
    }
    if(carry > 0){
        cur.next = new ListNode(carry);
    }
    return dummy.next;
}

Last updated

Was this helpful?