Javascript Link List reference

為{幸葍}努か 提交于 2019-12-08 05:42:10

问题


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

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.


回答1:


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

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



回答2:


I think you don't change the reference to the head in the returning object. You are changing the variable on the top of the function LinkedList, but you are returning a new reference at the bottom.



来源:https://stackoverflow.com/questions/11840506/javascript-link-list-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!