【问题标题】:javascript looped linkedlistjavascript 循环链表
【发布时间】:2013-01-13 09:46:03
【问题描述】:

这段代码有什么问题?我想做一些类似于循环链表的东西。

    <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>

【问题讨论】:

    标签: javascript linked-list


    【解决方案1】:

    重写GetNext:

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

    当您只想获取链接节点并访问它的 text 时,在 GetNext 中重新分配 this.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;
        }
    }
    

    【讨论】:

    • @user1973846 不。您总是返回 this,而不是 next 实例。这种编程风格被广泛认为是不好的做法,因为它违反了引用透明原则en.wikipedia.org/wiki/…。你怎么知道你现在在链表中的哪个位置?如果在对 GetNext 进行一些调用后,您希望在 first 之后拥有原始的下一个元素,它将消失!
    • 谢谢。现在我明白我的错误了。到达定义结构的末尾后,我用当前对象返回第一个对象,因为我重新分配了它。
    猜你喜欢
    • 2014-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多