Home > Mobile >  Add two numbers: leetcode - java solution
Add two numbers: leetcode - java solution

Time:10-16

I'm trying to figure out the Java solution for the problem Add two number from Leetcode.

This is the Java solution but i have a question. Why the dummyHead.next return the result when in the while cicle never assigned the number to this listnode. How works curr assign to dummyHead if curr is equal to dummyHead not the other way?

class Solution {
// Add Two Numbers (Java improved)
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummyHead = new ListNode(0);
    ListNode curr = dummyHead;
    int carry = 0;
    while (l1 != null || l2 != null || carry != 0) {
        int x = (l1 != null) ? l1.val : 0;
        int y = (l2 != null) ? l2.val : 0;
        int sum = carry   x   y;
        carry = sum / 10;
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        if (l1 != null)
            l1 = l1.next;
        if (l2 != null)
            l2 = l2.next;
    }
    return dummyHead.next;
}

}

CodePudding user response:

The important bit is new ListNode(0) that is what dummyHead and curr start with. Not different ListNode(s). So if you swapped curr and dummyHead like

ListNode curr = new ListNode(0);
ListNode dummyHead = curr;

it would behave the same way.

CodePudding user response:

LinkedList always have two fields: one is value and second one is the pointer to next node. If it's last node than next points to null.

Here in the code you mentioned:

Line 1-3 : generate new result linkedlist head using dummyHead and assign a variable curr to that head for moving and assigning purposes.

Carry is only used to check if sum is greater than 10 will be forwarded to next iterations.

In while loop: we are looping untill all the values become null.

If one or two value is null than we are assiging 0 using ternary oprator, and generating sum.

After sum is generated modules will be consider as carry and divison will be consider as value of node.

After loop is done we are returning head of linkedlist using the variable we have created.

It should be dummyHead.next as dummyHead is the node 0 we have intialized, but actual result starts from the next value.

  • Related