Very simple linked list

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).

by Yurii Predborskyi

HTML

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