Circular, Doubly Linked List, How To Manage The Node To Object Relationship?
This LinkedList function uses a very dodgy method to avoid client code needing to know about the linking nodes. Each list creates a unique string which is used to intrusively inser
Solution 1:
Here's my implementation:
function LinkedList(initialValues){
var head = null,
version = 0,
list = {
push: function(){
var args = [].slice.call(arguments, 0),
pushable = null;
while(args.length && (pushable = args.shift()))
head = new Node(pushable).append(head);
version++;
return this;
},
pop: function(){
var popped = head;
head = head.next();
version++;
return popped.value();
},
peek: function(){
return head && head.value();
},
iterator: function(){
return new Iterator(head, version);
},
toString: function(){
var vals = [],
iter = new Iterator(head, version);
while(iter.node()){
vals.push(iter.node().toString());
iter.step();
}
return ["("].concat(vals).concat(")").join(" ");
},
size: function(){
var iter = new Iterator(head, version);
while(iter.node()){
iter.step();
}
return iter.index();
}
};
return list.push.apply(list, initialValues);
function Node(input){
var content = input,
next = null;
return {
next: function(){
return next;
},
value: function(){
return content;
},
append: function(node){
next = node;
return this;
},
set: function(val){
return content = val;
},
toString: function(){
return content.toString();
}
};
}
function Iterator(base, v){
var current = base, index = 0,
checkSafe = function(){
if(v === version)
return true;
else
throw "The iterator is no longer valid, list modified.";
};
return {
node: function(){
checkSafe();
return current;
},
step: function(){
checkSafe();
current = current.next();
index++;
return this;
},
index: function(){
checkSafe();
return index;
}
};
}
}
Post a Comment for "Circular, Doubly Linked List, How To Manage The Node To Object Relationship?"