So the code explains things pretty well I think. I am using a closure to keep a method called reverseAll
private. reverseAll
is recursive but you don't need to worry about that I think. I am trying to reference this.head
in the reverseAll
function but I found it was undefined
. So I passed in a reference to this.head
and keep passing it through the recursive calls. Alas, it was not meant to be. I can just pull the reverseAll
method out of the closure and I will have a reference to this.head
. But I would like to know why my this.head
reference I pass in is not a "copy of a reference" or "a copy of a pointer" if you will like Javascript does when you pass in an object to a function. this.head
is a node
object by the way.
Here is the code (reference to jQuery is because the Stackoverflow snippet "IDE" failed when on line var obj = new LinkedList();
so I added a document.ready, jQuery not needed for any reason other than that:
function LinkedList() {
this.head = null;
};
LinkedList.prototype = (function () {
function reverseAll(current, prev, theHead) {
if (!current.next) { //we have the head
console.log('ending recursion, new head!!');
console.log('we have a refence to this.head in theHead or so I thought:');
console.log(theHead);
theHead = current;
theHead.next = prev;
console.log('theHead has a new "pointer":');
console.log(theHead);
return;
}
var next = current.next;
current.next = prev;
//keep passing the theHead reference through recursion
reverseAll(next, current, theHead);
};
return {
constructor: LinkedList,
reverse: function () {
console.log('clone head to iterate and change');
console.log('but also pass in reference of this.head obj as this.head is a node obj and this.head will be undefined in reverseAll()');
var headClone = JSON.parse(JSON.stringify(this.head));
reverseAll(headClone, null, this.head);
}
}
})();
LinkedList.prototype.add = function(value) {
var node = {
value: value,
next: null
};
var current;
if (this.head === null) {
this.head = node;
} else {
current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
return node;
}
LinkedList.prototype.remove = function(node) {
var current, value = node.value;
if (this.head !== null) {
if (this.head === node) {
this.head = this.head.next;
node.next = null;
return value;
}
//find node if node not head
current = this.head;
while (current.next) {
if (current.next === node) {
current.next = node.next;
return value;
}
current = current.next;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
var obj = new LinkedList();
for (var i = 1; i <= 10; i++) {
obj.add(i);
}
console.log('about to call obj.reverse()!');
console.log('obj.head:');
console.log(obj.head);
obj.reverse();
console.log('obj instance obj.head after reverse call, it has not changed!!:');
console.log(obj.head);
});
</script>