Reputation: 2971
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.
Upvotes: 1
Views: 1118
Reputation: 17899
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);
Upvotes: 1
Reputation: 3566
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.
Upvotes: 1