Skip to content

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

Description

@Lucien-X

因为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('======')
    }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions