Linked list in javascript

Ujjwal Gupta
1 min readAug 23, 2019

--

Introduction

Linked list is an important linear data structure which is used for dynamic memory allocation. Unlike arrays the data in linked list are not stored at continuous memory location but every element contains the reference of its next element.

Let’s Code

Let’s see how to implement linked list in javascript -

class NodeList {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.data = null;
}
add(data) {
const node = new NodeList(data);
if (this.data == null) {
this.data = node;
} else {
let root = this.data;
while (root.next != null) {
root = root.next;
}
root.next = node;
}
}
}
const list = new LinkedList();
list.add(5);
list.add(3);
list.add(9);

The logic of the above code is -

  • if there is no element at linked list root data then add the supplied element as root data.
  • else find the last of the root element which next value is null and then add the element at their next.

--

--

Ujjwal Gupta
Ujjwal Gupta

Written by Ujjwal Gupta

Building starscolab | Ex - Frontend lead Polygon | Creator of jsstore, fortjs | opensource creator | we3, blockchain, solidity | javascript

No responses yet