LinkedList is the dynamic data structure
as we can add or remove elements at ease, and it can even grow as needed.
Just like arrays,
linked lists store elements sequentially, but don’t store the elements contiguously like an array.
A linked list is a linear data structure similar to an array.
However, unlike arrays, elements are not stored in a particular memory location or index.
Rather each element is a separate object that contains a pointer or a link to the next object in that list.
Each element (commonly called nodes) contains two items: the data stored and a link to the next node.
An advantage of Linked Lists
- Nodes can easily be removed or added from a linked list without reorganizing the entire data structure. This is one advantage it has over arrays.
Disadvantages of Linked Lists
Search operations are slow in linked lists
Unlike arrays, random access of data elements is not allowed
Nodes are accessed sequentially starting from the first node.
It uses more memory than arrays because of the storage of the pointers.
Inserting a node at the beginning of a linked list
class node {
constructor(data,next = null)
{ this.data = data;
this.next = next;
}
}
class LinkedList {
constructor(){
this.head = null;
this.size = 0; }
insertFirst(data){
this.head = new node(data,this.head);
}
}
const obj = new LinkedList();
obj.insertFirst(400); obj.insertFirst(200);
console.log(obj);