Create A Linked List In JavaScript

Are you searching for linked list in javascript? Well you are not alone, many people on the internet are searching for data structures in javascript, In this post, I will teach you how to create a linked list in javascript. Also, we have earlier discussed same thing in C. So you can visit there if you want to learn data structures using C.

What Is Linked List?

Most of you might know that it is a data structure. But more specifically linked list is a linear data structure. By linear I want to say arranged in or extending along a straight or nearly straight line.

By definition, Linked List is a linear data structure which contains node, each node have two parts data and reference, where reference is a pointer which stores address of another node and the last node’s reference points to null.

But why we are learning linked list? What’s the point of it, you may want to ask. To answer such question let’s dive into the advantages.

Advantages of Linked List

  1. Dynamic DS : It can grow or shrink at runtime, by allocating and deallocating memory.
  2. No memory wastage : Only the required memory is used.
  3. Insertion And Deletion : Quite easier than array as there is no need to shift elements.

How To Create A Linked List In JavaScript?

class Node
{
    constructor(val)
     {
            this.data = val;
            this.next = null;
      }
}
var head = null;
var head = new Node(5);
var middle = new Node(10);
var last = new Node(15);

head.next = middle;
middle.next = last;
last.next = null;

var temp = head;
while(temp != null)
{
    document.write(temp.data);
    temp = temp.next;
}

In the above code we are doing following things:

  • Creating a class Node and initialize the node object with constructor.
  • Then we are initializing the data with given value and next as null.
  • Initialize the head as NULL.
  • Then creating three node head, middle, and last.
  • After this we are linking the node using next pointer.
  • And by using loop we are traversing and printing each node.

That’s all.

Shares
facebook sharing button Share
twitter sharing button Tweet
whatsapp sharing button Share
telegram sharing button Share
pinterest sharing button Pin

Leave a Comment