Linked list. In JavaScript we often build up an array of elements. Sometimes an algorithm may be helped by a linked list—less array resizing is needed.
With a two-element array, we can store a "current" value and "next" pointer. Then to loop over the linked list, we can access all the next pointers.
Example program. Let us begin. This program has a global variable called "list." This is an array of linked lists. Each "head" of a linked list is at an index in this list.
Info Add() method adds an element at an index in the linked list. The current value (even if undefined) is placed as the "next" value.
Then Display() loops over the pairs in the linked list at a certain index. It stops when an undefined "next" pointer is encountered.
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);ITEM: frog
ITEM: bird
ITEM: cat
::END::
ITEM: green
ITEM: blue
::END::
Avoid resizing arrays. This is not often a performance problem, but with linked lists we can avoid resizing arrays. And if we have existing objects we can reuse them for linking.
A summary. In most situations a linked list is not the best solution. But occasionally it can benefit a program: it may use less code and require less array resizing.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 28, 2023 (edit).