Are there any adventage of using linked lists in javascript? Its main adventage over arrays (for example) is that we can insert element at random index without moving every element and that they are not limited to size as arrays.
However, arrays in JS are dynamically expanded, shrink, and arrays are faster to access data. We can also use Array.prototype.splice()
method (indeed linked lists could be still faster than this one) to insert data.
Are there any advantages (speed and so on) of using linked lists over arrays in JavaScript then?
Code of basic linked lists using JS.
function list() {
this.head = null;
this.tail = null;
this.createNode=function(data) {
return {data: data, next: null }
};
this.addNode=function(data) {
if (this.head == null) {
this.tail = this.createNode(data);
this.head = this.tail;
} else {
this.tail.next = this.createNode(data);
this.tail = this.tail.next;
}
};
this.printNode=function() {
var x = this.head;
while (x != null) {
console.log(x.data);
x = x.next;
}
}
}
var list = new list();
list.addNode("one");
list.addNode("two");
list.printNode();
In a linked list if you are prepending or appending elements at the front or at the back then the time complexity is O(1), however it is O(n) for an array. However if you are retrieving an element from an array using the index then the time complexity will be O(1) against the linked list which would be O(n).
So it depends as to what you are trying to do, you need to create benchmarks and then test it as to which operation is taking how much time.
You can check the wiki:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With