"TypeError: Cannot set properties of undefined (setting 'next')"

"TypeError: Cannot set properties of undefined (setting 'next')"

输入:给定两个非空链表,表示两个非负整数。数字以相反的顺序存储,并且它们的每个节点都包含一个数字。将两个数字和 return 相加作为链表。

Input & Output Illustration (open for understanding)

var addTwoNumbers = function(l1, l2) {
let carry = 0,
    sum = 0;
let runningNode = new ListNode(0, null);
let headNode = runningNode;

while (l1 !== null || l2 !== null) {

    sum = l1 != null ? l1.val : 0 + l2 != null ? l2.val : 0 + carry;
    carry = 0;
    // Error is in below line it states "TypeError: Cannot set properties of undefined (setting 'next')" 
    runningNode.next = ListNode(sum % 10, null)
    runningNode = runningNode.next;
    //How to fix it?
    if (l1) {
        l1.next;
    }
    if (l2) {
        l2.next;
    }
}

if (carry) {
    runningNode.next = ListNode(carry);
}

return headNode;

};

几个问题:

  • 调用构造函数时需要new,否则this未定义,this.next等引用无效。您的代码中有两个地方需要进行此更正。

  • 在对 sum 的赋值中,+ 运算符优先于 ? : 运算符,但在您的情况下您希望采用另一种方式,所以您需要添加括号。

  • carry 永远不会设置为除 0 以外的任何值。当总和大于 9 时它应该得到 1。

  • 最终结果总是return一个以0开头的列表,也就是head所指的虚拟节点。这使得结果大十倍。 Return下一个节点。

更正后的代码:

var addTwoNumbers = function(l1, l2) {
    let carry = 0,
        sum = 0;
    let runningNode = new ListNode(0, null);
    let headNode = runningNode;
    while (l1 !== null || l2 !== null) {
        // Use parentheses to make sure the addition happens last:
        sum = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + carry;
        // Need to set carry
        carry = Math.floor(sum / 10); 
        // Need "new" when calling constructor
        runningNode.next = new ListNode(sum % 10, null); 
        runningNode = runningNode.next;
        // Must assign!
        if (l1) {
            l1 = l1.next;
        }
        if (l2) {
            l2 = l2.next;
        }
    }
    if (carry) {
        // Must call with "new":
        runningNode.next = new ListNode(carry);
    }
    return headNode.next; // skip the zero node
};