Linked Lists in JavaScript With ES6

Linked Lists in JavaScript With ES6

Linked Lists in JavaScript with ES6.This series is about data structure implementation in JavaScript using the ES6 specification.. Let's see how to make a singly linked list in Javascript… ... list in Javascript. We'll be using ES6 syntax throughout.

This is a continuation of a previous piece where we digested all surrounding concepts, pros and cons, Big O time complexity, real use cases, linked-list mainly operations, and all that kind of theory. If you have not read it yet, I recommend you read it first.

This series is about data structure implementation in JavaScript using the ES6 specification.

The aim of this second piece is to walk through the implementation of a linked list. Actually, the two pieces enclose a linked list itself since the prior piece is pointing to this one.

The Node Class

In the next code, we’re going to define our Node class with its constructor. Remember, the node is the basic building block to store the data and the next pointer.

This class will have to handle the node creation. Every time the class is instantiated, the constructor has the responsibility to initialize the two properties: data and next.

Node Class Node Class

Now the challenge is to create the next four nodes (just nodes creation, not how to connect them).

Linked List Linked List

Basically, we have to instantiate the Node class four times in order to create the four nodes.

Creating Nodes Creating Nodes

At this point, we don’t care about the second parameter. Why? Because at this moment, we’re just learning how to create the node without having to worry about how they’ll be connecting together.

How Can We Connect the Nodes?

In the prior code, we just created nodes independently. Now is time to learn how to connect them to form the linked list.

Connecting nodes Connecting nodes

We have defined the Node class. Next is to define a new class that will handle the nextpointer property and the main operations in the linked list. Let’s create the LinkedList class.

Linked List Class Linked List Class

In the above code, we have just defined a class called LinkedList with its constructor. This has the work of initializing the headproperty, to store the first node,and size, to keep track of the size of the linked list.

Next is to offer the ability to insert to the head, to the tail, or at any random position in the list.

Inserting Into the Head

Inserting to head Inserting to head

We have just created a simple method to add nodes to the head of the linked list. We are passing down to it the dataparameter and setting a value for the this.head property creating a new instance of the Node class.

Let’s do some tests of its implementation so far and see the results.

This is image title

The output will be:

Linked list output Linked list output

Inserting at the Tail

We just learned how to add nodes to the head. It’s time to know how to add nodes to the tail.

Inserting at the tail Inserting at the tail

In the aboveinsertToTail function, we are passing down the data parameter, and then we created a new instance of the Node class. After that, we are checking if the head is empty. If so, the head itself will be set to the new node we have just after created. Otherwise, set the tail with the head and then loop through the linked list to find the tail and update the tail’s next pointer.

Inserting at Random Position

Finally, we are going to see how to insert a new node in the linked list at a given random position. For this, we have to traverse the list until we find the desired position.

Inserting at a given random position

Inserting at a given random position

Now we are going to test this function using the next tests.

This is image title

The output will be as below. As you can see, at the given index, the node (600) was added at the second index of the list.

This is image title

The Whole Code

class Node {
  constructor(data, next = null) {
    this.data = data;
    this.next = next;
  }
}

//Let's create four nodes
let node1 = new Node(5);
let node2 = new Node(10);
let node3 = new Node(20);
let node4 = new Node(1);

//connecting nodes
node1.next = node2;
node2.next = node3;
node3.next = node4;

//LinkedList Class
class LinkedList {
  constructor() {
    this.head = null; //first node of the Linked List
    this.size = 0; //Track size of the linked list
  }
  //Insert to head
  insertToHead(data) {
    this.head = new Node(data, this.head);
    this.size++;
  }

  //Insert into the tail
  insertToTail(data) {
    const node = new Node(data);
    let tail = null;
    //if empty, make it head
    if (!this.head) {
      this.head = node;
    } else {
      tail = this.head;
      while (tail.next) {
        tail = tail.next;
      }
      tail.next = node;
    }
    this.size++;
  }

  //Insert at random position
  insertAt(data, index) {
    //if it's empty
    if (!this.head) {
      this.head = new Node(data);
      return;
    }
    //if it needs add to the front of the list
    if (index === 0) {
      this.insertToHead(data); //reuse insertToHead function
      return;
    }
    let node = new Node(data);
    let current, previous;
    let count = 0;
    // current will be first
    current = this.head;
    while (count < index) {
      previous = current;
      count++;
      current = current.next;
    }
    node.next = current;
    previous.next = node;
    this.size++;
  }
}

const linkedList = new LinkedList();
linkedList.insertToHead(100);
linkedList.insertToHead(200);
linkedList.insertToHead(300);
linkedList.insertToTail(400);
linkedList.insertAt(600, 2);

console.table(linkedList);

LinkedList.js

I hope you have gained more knowledge about data structure and especially with Linked list. That’s all for now.

Thanks for reading!

javascript ES6

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Learn Modern JavaScript ES6 | ES7 | ES8

In this article we are going to Learn Modern JavaScript [ ES6 | ES7 | ES8 ] , so as you know JavaScript is a scripting language that was introduced for

The essential JavaScript concepts that you should understand

The essential JavaScript concepts that you should understand - For successful developing and to pass a work interview

JavaScript ES6 Classes

An exciting new construct that was introduced in the ES6 specification is the ES6 classes. If you're a Javascript developer, you will be aware that Javascript follows prototypal inheritance and sometimes it can get a little messy. However, with ES6 classes the syntax is simpler and much more intuitive.

JavaScript: Template Literals (ES6)

Beginners Guide to Template Literals in JavaScript. JavaScript: Template Literals (ES6). Inthis article, I will discuss another powerful feature of modern JavaScript; template literals, which was released in the 2015 edition of the ECMAScript specification and was referred to as template strings prior to ES6. Similar to string interpolation features in other languages like Ruby and Phyton, template literals provide syntactic sugar that allows us to construct strings more quickly. Before template literals were added to the JavaScript language in ES6, single quotes (‘ ’) and double quotes (“ ”) were the only ways to make a string. Template literals offer another way to declare strings that makes use of backtick (` `) character.

What’s the difference between Var, Let and Const in JavaScript?

In the not so distant past there was only one way to define a variable in JavaScript, and that was with var. However…