Javascript链接列表参考 [英] Javascript Link List reference

查看:39
本文介绍了Javascript链接列表参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Javascript创建一个链表对象,然后尝试将其反转.

I wanted to create a Linked List object in Javascript and I try to reverse it.

我认为这是一个非常简单的问题,但是我莫名其妙地陷入了困境.这是我的代码.

I assume this is a really simple question, but I somehow got stuck. Here is my code.

var Node = function (val) {
 this.value = val;
 this.next = null;
};

var LinkList = function (node) {
     var head = node;

     function append(val) {...}; //works fine
     function toString() {...}; //works fine

     function reverse() {
        if (!head.next) {
            return;
        } 
        var prev = head;
        var cur = head.next;
        while (cur) {
           var temp = cur.next;
           cur.next = prev;
           prev = cur;
           cur = temp;
        }
        head = prev;
     }

     return {head: head, append: append, toString: toString, reverse: reverse}
}

然后,我将10个项目附加到链接列表",并对其进行反向调用.它能够反转所有节点,但无法将头重置为列表的末尾,但与原始头保持相同.

Then, I append 10 items to the Link List and call reverse on it. It is able to reverse all the node, but it fails to reset the head to the end of the list, but stay the same as the original head.

请说明为什么不将磁头复位到列表的末尾.

Please explain why the head is not being reset to the end of the list.

推荐答案

一旦返回对象,就无法通过其单独的引用来修改其属性.只有函数会关闭引用.对象没有.

Once you return the object, you can't modify it's properties by their individual references. Only functions close over references. Object's don't.

您需要保存对整个返回对象的引用,并直接修改其头部.

You need to save the reference to the whole returned object and modify it's head directly.

总的来说,有更好的方法来创建类似的复杂对象(请参见原型).

Overall though, there are better ways to create complex objects like that (see prototypes).

此外, Node 是全局浏览器.使用其他名称,因为它已经表示DOM Node接口.

Also, Node is a browser global. Use other name, as It already represents DOM Node interface.

因此,请牢记以上所有内容:

So, keeping in mind all the above:

var LinkedList = function (node) {
    this.head = node;
};

LinkedList.prototype.append = function (val) { /* ... */ };

LinkedList.prototype.toString = function () { /* ... */ };

LinkedList.prototype.reverse = function () {
    if (!this.head.next) {
        return;
    }

    var prev = this.head;
    var cur = prev.next;
    while (cur) {
        var temp = cur.next;
        cur.next = prev;
        prev = cur;
        cur = temp;
    }
    this.head = prev;
};

var linkedList = new LinkedList(someNode);

这篇关于Javascript链接列表参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆