A very basic linked list structure in javascript to make it possible to traverse a number of items in O(n) time total where adding to the list is done in O(1) time and finding next element is O(1) and items are processed in FIFO order.
If you don't keep a pointer to the start of the list, old elements will be erased from memory (will become inaccessible and will be garbage-collected).
Self-destructing linked list
This implementation of linked list collection is supposed to allow one to traverse a linked list from CURRENT node till the end of the list. There is no head, (unless you make a reference to it and assign it to a value), thus you can't go back. But you should be able to go over every element in the traditional manner (from starting point and via next pointers).
The purpose of this excercise is to make minimal structure for a linked list so I don't have to copy-paste large blocks of code into small programs just to support linked lists for LeetCode fiddles :D
JavaScript
// single-line linked list
const list = function (x) { return {val:x, next:null}};
// head pointer for the start of the linked list, if you don't keep it you lose the ability to go over the list again
let head = new list('a');
// set pos to start of the list
let pos = head;
for (let i = 0; i < 5; i++) {
// rewrite next pointer to a new list node
pos.next = new list(i);
// point pos at the newly made node (tail) so that we can add to tail
pos = pos.next;
}
// since we kept "head", we can revisit the list
console.log(head);
// if you don't keep a separate "head" pointer, you won't be able to traverse the list again
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.