BakMamba74
BakMamba74

Reputation: 51

Adding two numbers where each number is in a linked list in reverse order

I'm practicing algorithms and solving https://leetcode.com/problems/add-two-numbers/. I'm doing this in JavaScript. I am able to get the correct number but not able to return the answer as a backwards linked list. Can someone please help me find the error in my code and complete this last step?

I was able to iterate backwards through both linked lists by using unshift (adding each to the front of an array). Then did a join on the arrays and called parseInt to convert them to integers. Adding them is trivial so no problems there. The problem for me comes in the question saying that the function should return a linked list (reverse order). I'm unable to successfully access the value of newly created node. Granted I don't think they used es6 syntax in the LinkedList class but still.

function ListNode(val) {
    this.val = val;
    this.next = null;
}

@param {ListNode} l1
@param {ListNode} l2
@return {ListNode}

var addTwoNumbers = function(l1, l2) {
    let num1 = [];
    let num2 = [];
    let current1 = l1;
    let current2 = l2;
    while(current1){
        num1.unshift(current1.val);
        current1 = current1.next;
        console.log(num1);
    }
    while(current2){
        num2.unshift(current2.val);
        current2 = current2.next;
        console.log(num2);
    }
    let number1 = parseInt(num1.join(''));
    console.log(number1);
    let number2 = parseInt(num2.join(''));
    console.log(number2);
    console.log("Number 1 is " + number1);
    console.log("Number 2 is " + number2);
    let result = number1 + number2;
    console.log(result);
    let liststr = result.toString();
    console.log(liststr);
    let node = new ListNode();
    let current = node;
    for (let i = liststr.length - 1; i >= 0; i--){
        if(current.val !== undefined){
            node.next = new ListNode(liststr[i]);
            current = current.next;
        }
        else {
            node.value = liststr[i];
            current = current.next;
        }
    }
    return node;
};

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Expected Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. 807 should be converted to a linked list 7->0->8 I'm getting a runtime error "TypeError: Cannot read property 'val' of null".

Upvotes: 1

Views: 316

Answers (1)

Shoyeb Sheikh
Shoyeb Sheikh

Reputation: 2866

For the error "TypeError: Cannot read property 'val' of null", I would suggest you to change your condition to,

if( current && current.val){

Because you are getting null in current and you can't access any property (val in this case) of null.

Upvotes: 1

Related Questions