Create a Class in Javascript called Chain. The 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.
Make a Chain consisting of 5 links. 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.
This is a demonstration of the concept of making a Linked List (in this case we call it a chain in JavaScript). There are 2 object involved here - and this is a very easy conceptual way to do this.
< br/>
< br/> Add Link Name:
< input type="textbox" id="LinkName" Value="New Link" />
< input type="button" id="AddLink" value="Add Link" onClick="addLink();" />
< input type="button" id="DisplayHead" value="Display Chain Head" onClick="displayChainHead();" />
< p id="demo">
// a single link chain
var chain = new Chain('Link 1');
function addLink() {
var newLinkName = document.getElementById("AddLink").value;
alert("Adding a Link Named: " + newLinkName);
chain.addLink(newLinkName);
chain.print();
}
function displayChainHead() {
// This should print output
document.getElementById("demo").innerHTML = chain.head.asString();
}
// Define the link object
function Link(_id, _value, _next) {
// This is a possible implementation of a Link - this requires 3 pieces of information and links have an ID. Note - also not required for successful implementation.
this.id = _id; // The id of the current link
this.value = _value; // The value stored
this.next = _next; // a pointer to the next link, this is 0 if it is the last link in the chain
}
Link.prototype.asString = function() {
return "Link: " + this.id +
" Value:" + this.value +
" Points To: " + this.next + "
";
}
Link.prototype.setPointer = function(_next) {
// A way to implement this is to be able to set the pointer of one link to a value of the next. Note that links can also point backwards as they are a list. They could also point in both directions (next and last)
}
// Define the Chain object
function Chain(_firstValue) { // We will define the chain with the first link defined
this.length = 1;
// I like to keep track of the first link, not really necessary way to do this but one of the ways of implementing a linked list
this.head = new Link(1, _firstValue, 0);
}
Chain.prototype.lastLink = function() {
// A function to find the last link in the chain - "i need this piece"
}
Chain.prototype.addLink = function(_linkValue) {
// A function to add a link to the chain "i need this piece".
}
Chain.prototype.print = function() {
// And i nee all the links in the chain to printout
}