当没有使用return语句时,会发生无限循环

时间:2018-01-07 18:24:48

标签: typescript linked-list infinite-loop

这是一个初学者问题。

我有两个简单的类,旨在创建一个链接列表。如果在if语句中没有使用return语句,则LinkedList类中的append方法会导致无限循环。任何人都可以提供一些见解,为什么会这样?

$id

2 个答案:

答案 0 :(得分:0)

我认为这里的问题在于LinkedList的初始化。一开始,列表为空:

const linkedList = new LinkedList(); // linkedList = {head: undefined}

然后当你把第一个项目添加到列表中时:

linkedList.append(new Nodule(42)); 

发生以下情况:

append(appendedNodule: Nodule) { // appendedNodule = {data: 42, next: undefined}
    if (!this.head) { // Condition evaluates to true, since we just initialized the LinkedList
        this.head = appendedNodule; // linkedList = {head: {data: 42, next: undefined}}
    }
    let current: Nodule = this.head; 
    // current = {data: 42, next: undefined}

    // current.next is undefined, so we skip this loop entirely
    while (current.next) {
        current = current.next;
    };

    // current.next = current now! We've created a circular reference!
    current.next = appendedNodule;

}

似乎问题在于此处的分支。如果列表为空,我们只需要使用提供的head实例定义Nodule。否则,我们需要附加到列表的末尾。我认为包装

let current: Nodule = this.head;
while (current.next) {
    current = current.next;
};
current.next = appendedNodule;
else块中的

可以解决问题: - )

答案 1 :(得分:-1)

让我们为您追加的第一个节点逐行执行代码:

    if (!this.head) {

这种情况是真的:还没有头脑。所以if块被执行

        this.head = appendedNodule;

所以现在我们有一个头节点,它是附加的节点。没有回报,所以我们继续执行该方法。

    }
    let current: Nodule = this.head;

我们现在还有一个局部变量current,它也引用了头(不再是null),它也是附加的节点。

    while (current.next) {

当前磁头没有下一个节点,因此不会执行while块

        current = current.next;

因此不执行上述指令

    };

但是下面的一个是,因为我们不再在while循环中了

    current.next = appendedNodule;

现在头部有一个下一个节点,下一个节点本身就是。

因此,如果我们现在追加另一个节点,while循环将一次又一次地获取下一个节点,直到它为空。但它永远不会为空,因为你已经创建了一个循环:

 ---------\
 |        | next
 \/       |
current ---

让我们第二次逐行执行相同的方法:

    if (!this.head) {

条件现在是假的。我们有一个头节点,播种跳过if块

        this.head = appendedNodule;
    }
    let current: Nodule = this.head;

当前变量返回头节点

    while (current.next) {

这是事实,因为头节点的下一个节点本身就是这样。所以我们执行while块

        current = current.next;

当前成为下一个节点。所以我们再次测试while条件。它仍然是:下一个节点是当前节点。所以我们有一个无限循环。

    };