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
}
}
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()
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 listJavaScript 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.
Simple Linked List Implementation in JavaScript
Visit Course Simple Linked List Implementation in JavaScript Linked List Implementation in JavaScriptRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4