【问题标题】:Recalling function on same input causing loops在相同的输入上调用函数导致循环
【发布时间】:2021-10-14 22:44:55
【问题描述】:

编写了以下函数来合并两个链表:

var mergeTwoLists = function(l1, l2) {
    current = l1.head;    
    if (current === null){
        l1.head = l2.head; //Have to use l1.head instead of current since if we assign current again to l2.head the current will just start pointing to l2.head and lose reference to l1.
    }    
    else{        
        while( current.next != null){            
            current = current.next;            
        }        
        current.next = l2.head;        
    }    
    return l1;
};

创建两个链表:

let l1 = new linkedlist();
let l2 = new linkedlist();
l1.insert(1);
l1.insert(2);
l1.insert(4);
l2.insertEnd(1);
l2.insertEnd(3);
l2.insertEnd(4);

现在我调用了两次函数:

let l3 = mergeTwoLists(l1,l2);
console.log(l3.show());
let l4 = mergeTwoLists(l1,l2);
console.log(l4.show())

第一个节目输出预期的 4 2 1 1 3 4。但是,第二个调用继续无限循环并继续输出 4 2 1 1 3 4 1 3 4 1 3 4 1 3 4 ...... ..

为什么会这样?

【问题讨论】:

    标签: javascript linked-list


    【解决方案1】:

    mergeTwoLists 不会复制列表节点。所以第一次合并后,l1的最后一个节点和l2的最后一个节点是一样的。当你再次合并它们时,l2 中最后一个节点的next 属性现在指向l2.head,从而产生一个循环列表,就像你完成了mergeTwoLists(l2, l2) 一样。

    如果你不希望这种情况发生,你应该定义一个copyList() 函数,并使用

    current.next = copyList(l2).head;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      • 1970-01-01
      • 2019-11-01
      相关资源
      最近更新 更多