Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

数据结构》链表:循环链表会导致display方法死循环 #3

Open
Lucien-X opened this issue Jul 23, 2017 · 0 comments
Open

Comments

@Lucien-X
Copy link

因为insertAfter方法中,新插入的元素next指向下一元素,
将head的next指向自己,会导致最后一个元素的next永远指向head,
这个逻辑就是传说中的"衔尾蛇",
会使链表变为循环链表,从而使得不加终止判断的display方法陷入死循环
display方法修改如下,望修正

// 显示全部节点
    display: function () {
        var current = this.head
        // 加入终止判断,到最后一个元素(next指向head)结束,防止双向链表中发生死循环
        while (current.next&&current.next.data!='head') {
            console.log(current.next.data)
            current = current.next
        }
        console.log('======')
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant