Implementation of LinkedList in Javascript (original) (raw)

Last Updated : 05 Mar, 2025

In this article, we will be implementing the LinkedList data structure in Javascript.

A linked list is a linear data structure where elements are stored in nodes, each containing a value and a reference (or pointer) to the next node. It allows for efficient insertion and deletion operations.

**Syntax

class Node{
constructor(value)
{
this.value=value
this.next=null
}
}

Implementation of a linked list

1. Creaing a Linked List

To create a simple linked list in JavaScript, the provided code defines a LinkedList class and a Node class to represent individual elements.

JavaScript `

class Node{ constructor(value) { this.value=value this.next=null } } class LinkedList{ constructor() { this.head=null } append(value) { let newnode=new Node(value) if(!this.head) { this.head=newnode return } let current=this.head while(current.next) { current=current.next } current.next=newnode

}
printList(){
  let current=this.head
  let result=""
  while(current)
  {
      result+=current.value+'->'
      current=current.next
  }
  console.log(result+'null')
}

} let list=new LinkedList() list.append(10) list.append(20) list.append(30) list.printList()

`

2. Operations on Linked List

This code demonstrates the basic functionality of a singly linked list in JavaScript, with methods for appending, printing, and deleting nodes.

JavaScript `

class Node { constructor(value) { this.value = value; this.next = null; } } class LinkedList { constructor() { this.head = null; } append(value) { let newnode = new Node(value); if (!this.head) { this.head = newnode; return; } let current = this.head; while (current.next) { current = current.next; } current.next = newnode; } printList() { let current = this.head; let result = ""; while (current) { result += current.value + "->"; current = current.next; } console.log(result + "null"); } delete(value) { if (!this.head) { console.log("list is empty no element to delete"); return; } if (this.head.value === value) { this.head = this.head.next; return; } let prev = null; let current = this.head; while (current && current.value !== value) { prev = current; current = current.next; } if (!current) { console.log("value is not found in list"); return; } prev.next = current.next; } } let list = new LinkedList(); list.append(10); list.append(20); list.append(30); list.delete(20); list.printList();

`

To study more refer to this article Linked List data structure

Use cases of linked list

Advantages of a Linked List

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.

Similar Reads

Mathematical









Recursion







Array








Searching






Sorting












Hashing



String







Linked List