Types of Linked List in Javascript


In this article, we are going to discuss various types of linked lists in JavaScript. A linked list is a sequential data structure that stores data dynamically. Since, this data structure is not indexed, the data can be added and removed as seen fit. This will reduce the wastage of memory storage.

There are various types of linked list. They are as follows −

  • Simple Linked List − Item Navigation is forward only.
  • Doubly Linked List − Items can be navigated forward and backward way.
  • Circular Linked List − Last item contains link of the first element as next and the first element has a link to the last element as prev.

Simple linked list

Example 1

The following example shows how to create a simple linked list. We create a Node class with two variables local to it − data and next. Whenever this class is called, the constructor assigns the data value to the data variable and links it to the previous node already present in the list.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Linked List Data Structure</title>
   </head>
   <body>
      <script type="text/javascript">
         class Node {
            constructor(data) {
               this.element = data;
               this.next = null;
            }
         }
         class LinkedList {
            constructor() {
               this.head = null;
               this.size = 0;
            }
            add(element) {
               let node = new Node(element);
               let temp;
               if (this.head == null) this.head = node;
               else {
                  temp = this.head;
                  while (temp.next) {
                     temp = temp.next;
                  }
                  temp.next = node;
               }
               this.size++;
            }
            insertAt(element, index) {
               if (index < 0 || index > this.size)
               return document.write("Enter a valid index.");
               else {
                  let node = new Node(element);
                  let curr, prev;
                  curr = this.head;
                  if (index == 0) {
                     node.next = this.head;
                     this.head = node;
                  } else {
                     curr = this.head;
                     let it = 0;
                     while (it < index) {
                        it++;
                        prev = curr;
                        curr = curr.next;
                     }
                     node.next = curr;
                     prev.next = node;
                  }
                  this.size++;
               }
            }
            removeFrom(index) {
               if (index < 0 || index >= this.size)
               return document.write("Enter a valid index");
               else {
                  let curr,
                  prev,
                  it = 0;
                  curr = this.head;
                  prev = curr;
                  if (index === 0) {
                     this.head = curr.next;
                  } else {
                     while (it < index) {
                        it++;
                        prev = curr;
                        curr = curr.next;
                     }
                     prev.next = curr.next;
                  }
                  this.size--;
                  return curr.element;
               }
            }
            removeElement(element) {
               let curr = this.head;
               let prev = null;
               while (curr != null) {
                  if (curr.element === element) {
                     if (prev == null) {
                        this.head = curr.next;
                     } else {
                        prev.next = curr.next;
                     }
                     this.size--;
                     return curr.element;
                  }
                  prev = curr;
                  curr = curr.next;
               }
               return -1;
            }
            indexOf(element) {
               let count = 0;
               let temp = this.head;
               while (temp != null) {
                  if (temp.element === element) {
                     document.write("</br>The Element is found at the index : ");
                     return count;
                  }
                  count++;
                  temp = temp.next;
               }
               return -1;
            }
            isEmpty() {
               return this.size == 0;
            }
            size_of_list() {
               document.write("</br>The size of the Linked List is : " + this.size);
            }
            displayList() {
               let curr = this.head;
               let str = "";
               while (curr) {
                  str += curr.element + " ";
                  curr = curr.next;
               }
               document.write("The Elements in the Linked List are: " + str);
            }
         }
         let ll = new LinkedList();
         ll.add(10);
         ll.add(20);
         ll.add(30);
         ll.add(40);
         ll.add(50);
         ll.displayList();
         ll.size_of_list();
         document.write(ll.indexOf(40));
      </script>
   </body>
</html>

Doubly Linked list

The doubly linked list is a type of linked list links the nodes present in it, in two ways. In simple words, a node in a doubly linked list is connected to its previous node and the next node. Therefore, items can be navigated forward and backward way.

Example 2

The following example shows how to create a doubly linked list and perform its operations using JavaScript. We first create a Node class containing three compartments: previous, value and next. Everytime this class is called, a new node is established in the list. Then we perform various linked list operations like insertion, deletion, checking status and display.

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Doubly Linked List Data Structure</title>
   </head>
   <body>
      <script type="text/javascript">
         function createNode(value) {
            return {
               value: value,
               next: null,
               previous: null,
            };
         }
         class DoublyLinkedList {
            constructor() {
               this.head = null;
               this.tail = null;
               this.size = 0;
            }
            insert(value) {
               this.size++;
               let newNode = createNode(value);
               if (this.tail) {
                  this.tail.next = newNode;
                  newNode.previous = this.tail;
                  this.tail = newNode;
                  return newNode;
               }
               this.head = this.tail = newNode;
               return newNode;
            }
            remove() {
               if (this.tail) {
                  this.size--;
                  let removedTail = this.tail;
                  let beforeTail = this.tail.previous;
                  this.tail = beforeTail;
                  if (this.tail) {
                     this.tail.next = null;
                  } else {
                     this.head = null;
                  }
                  return removedTail;
               }
               return undefined;
            }
            print() {
               document.write("The Elements in the Doubly Linked List are :</br> ");
               let current = this.head;
               while (current) {
                  document.write(
                    `${current.previous?.value}   ${current.value}   ${current.next?.value}`
                  );
                  current = current.next;
               }
            }
            insertHead(value) {
               this.size++;
               let newNode = createNode(value);
               if (this.head) {
                  this.head.previous = newNode;
                  newNode.next = this.head;
                  this.head = newNode;
                  return newNode;
               }
               this.head = this.tail = newNode;
               return newNode;
            }
            insertIndex(value, index) {
               if (index >= this.size) {
                  throw new Error("Insert index out of bounds");
               }
               if (index === 0) {
                  return this.insertHead(value);
               }
               this.size++;
               let currentNode = this.head;
               for (let i = 0; i < index; i++) {
                  currentNode = currentNode.next;
               }
               let previousNode = currentNode.previous;
               let newNode = createNode(value);
               newNode.next = currentNode;
               newNode.previous = previousNode;
               previousNode.next = newNode;
               currentNode.previous = newNode;
               return newNode;
            }
         }
         let dLinkedList = new DoublyLinkedList();
         dLinkedList.insert(7);
         dLinkedList.insert(8);
         dLinkedList.insert(9);
         dLinkedList.print();
      </script>
   </body>
</html>

Circular Linked List

Circular Linked lists can either be created as singly (simple) linked list or doubly linked list.

If it is simple linked list, the address of the first element will be stored in the next part of the last node but if it’s a doubly linked list, the last item contains a link to the first element as next and the first element has a link to the last element as prev.

Updated on: 16-Dec-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements