In Javascript using JSFiddle we are going to create a Class called Chain. If you
ID: 665480 • Letter: I
Question
In Javascript using JSFiddle we are going to create a Class called Chain. If you need a little primer on creating objects and classes in Javascript seehttp://www.w3schools.com/js/js_object_definition.asp - if you know your object oriented code this will be relatively straightforward. Your Chain will be made up of Links. Each link will have an id, a value (String) and a pointer to the next link ( NextLink ) - which is simply a pointer to the id of the next link in the Chain. Please note that this is a very inefficient representation of the Chain. Here is a simple Javascript code definition of a Link for you to use. https://jsfiddle.net/reaglin/q46obht6/
You will make a Chain consisting of 5 links. You will also create a print function for the chain that will print the links in link order. You may need to create some functions to support this functionality. Please post your complete code and include screenshots of your Fiddle if possible.
Explanation / Answer
var LinkedList = function(e){
var that = {}, first, last;
that.push = function(value){
var node = new Node(value);
if(first == null){
first = last = node;
}else{
last.next = node;
last = node;
}
};
that.pop = function(){
var value = first;
first = first.next;
return value;
};
that.remove = function(index) {
var i = 0;
var current = first, previous;
if(index === 0){
//handle special case - first node
first = current.next;
}else{
while(i++ < index){
//set previous to first node
previous = current;
//set current to the next one
current = current.next
}
//skip to the next node
previous.next = current.next;
}
return current.value;
};
var Node = function(value){
this.value = value;
var next = {};
};
return that;
};
var linkedList = new LinkedList();
linkedList.push(1);
linkedList.push(2);
linkedList.push(3);
linkedList.push(4);
linkedList.remove(0);
console.log(linkedList.pop());
console.log(linkedList.pop());
console.log(linkedList.pop());
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.