Linked Lists<br/>
<br/><br />
<input type="button" value="Create List" id="linked" />
<br /><br /> Name of Node being added:
<input id="LinkName" Value="A B C D E" />
<input type="button" value="Add Node to List" id="addNode" />
<p id="demo"></p>
<br />
JavaScript
var list = null;
document.getElementById("linked").onclick =function(){
createList();
}
document.getElementById("addNode").onclick =function(){
addNode();
}
function createList() {
var value = document.getElementById("LinkName").value;
list = new List(value);
document.getElementById("demo").innerHTML = list.print();
}
function addNode() {
var value = document.getElementById("LinkName").value;
list.addNode(value,list.last);
document.getElementById("demo").innerHTML = list.print();
}
// Define the link object
function Node(_value, _last) {
// This is a possible implementation of a Doubly Linked List
this.value = _value; // The value stored
this.last = _last; // A pointer to the previous link
this.next = null; // a pointer to the next link
return this; // returns the created node
}
Node.prototype.asString = function () {
return this.value + " ";
}
// Define the List object
function List(_value) {
this.length = 1;
this.head = new Node(_value, null);
this.last = this.head;
}
//Function to add node to list
List.prototype.addNode = function (_value,_last) {
var node = new Node(_value, _last);
if (this.length) {
this.last.next = node;
node.last = this.last;
this.last = node;
} else {
this.head = node;
this.last = node;
}
this.length++;
}
List.prototype.print = function () {
var s = "";
var n = this.head;
while (n != null) {
s += n.asString();
n = n.next;
}
return s;
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.