Linked List

2 min. read

Linked List

Although a linked list is similar to an array, it is not restricted to a declared number of elements. Additionally, unlike an array which stores data contiguously in memory or on disk, a linked list can easily insert or remove elements without reallocation or reorganization of the entire structure because the data items need not be stored contiguously.

Linked List Drawbacks:

  1. Random access is not allowed. We must access nodes sequentially starting from the first one. Therefore, we cannot do a binary search on a linked list. So for searching element is slow.

  2. Extra memory space for a link is required for each element of the list.

function LinkedList() {
this.head = null;
this.tail = null;
function Node(value, next, prev) {
this.value = value; = next;
this.prev = prev;

LinkedList.prototype.addToHead = function(value) {
const newNode = new Node(value, this.head, null);
if (this.head) this.head.prev = newNode;
else this.tail = newNode;
this.head = newNode;

As you see we created the method inside the LinkedList prototype, why? well this tecnique is useful because we are going to create many objects, and if we have not create our methods in the prototype we would be duplicating all the methods for each object which meant an expenditure in memory that could be harmful.