C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
AddToList: This method adds an element at an index in the linked list. The current value (even if undefined) is placed as the "next" value.
Display: This loops over the pairs in the linked list at a certain index. It stops when an undefined "next" pointer is encountered.
JavaScript program that creates linked list
var list = [];
function addToList(n, value) {
// Add to the list as this index.
// ... Place existing entry as second element in a new array.
// ... Replace current array.
list[n] = [value, list[n]];
}
function display(n) {
// Loop over and display linked list.
for (var pair = list[n]; pair; pair = pair[1]) {
console.log("ITEM: " + pair[0]);
}
console.log("::END::");
}
addToList(5, "cat");
addToList(5, "bird");
addToList(5, "frog");
addToList(1, "blue");
addToList(1, "green");
display(5);
display(1);
Output
ITEM: frog
ITEM: bird
ITEM: cat
::END::
ITEM: green
ITEM: blue
::END::
However: For small lists, sometimes linked lists are a better option. No branches are needed to add an element.