链接列表- javascript循环链接列表

linked list - javascript looped linkedlist

本文关键字:链接 列表 循环 javascript      更新时间:2023-09-26

这段代码有什么问题?我想做一些类似于循环linkedlist。

    <script type="text/javascript" charset="utf-8">
        function LinkedText(text, nextLinkedText) {
            this.text = text;
            this.next = nextLinkedText;
            this.AsNext= function() {
                this.text = this.next.text;
                this.next = this.next.next;
                return this;
            }
        }
        var first = new LinkedText('first')
        var last = new LinkedText('last', first);
        first.next = last;
        alert(first.text); //show 'firts'
        alert(first.AsNext().text); //show 'last'
        alert(first.AsNext().text); //show 'last' not 'first' why?
        alert(first.AsNext().text); //show 'last'
        alert(first.AsNext().text); //show 'last' not 'first' why?
    </script>

重写GetNext:

this.GetNext = function() {
    return this.next;
}

重新分配this是没有意义的。text在GetNext中,当你想要的只是获取链接节点并访问它的text

你可以这样使用:

var i = 0            // avoid infinite loop below
var maxruns = 10;    // avoid infinite loop below
var node = first;
while(node){
    doSomethingWithNode(node);
    node = node.GetNext();
    // avoid an infinite loop
    i++;
    if (i > maxruns) {
        break;
    }
}