How To Create A Linked List In Javascript | letsbug
Hi in this article we are learning how we can implement linked-list in javascript. We have already seen how we can implement stack data structure using linked lists and we are looking at the linked list themselves.
Linked list is a linear data structure which is more flexible than array. That is what i have to say about on defining them. You can learn more about them online we will just focus on implementing them in javascript. And perform operations on them.
List of operation on linked list that we will implement are:
- insert()
- append()
- print()
- length()
- deleteLast()
- deleteFirst()
- findAt()
We are implementing the singly linked list in which every node is linked with a next node. Which means node store the address of the node which will come next to it. But does not know or store from where is has come from or its previous node.
Linked List In Javascript
// Constructor Class for Ndoesclass Node {constructor(value, next = null) {this.value = valuethis.next = next}}// Wrapper Linked list classclass LinkedList {constructor() {this.head = nullthis.size = 0}//insert data to the start of the linkedListinsert(data) {let current = this.headthis.head = new Node(data, current)this.size++}//insert data to the end of the linkedListappend(data) {let current = this.headlet previous = currentwhile (current) {previous = currentcurrent = current.next}previous.next = new Node(data)this.size++}//print the linkedListprint() {let current = this.headwhile (current) {console.log(current.value)current = current.next}}// delete the last node in the linkedListdeleteLast() {let current = this.headlet previous = currentwhile (current.next) {previous = currentcurrent = current.next}previous.next = nullthis.size--}// delete the first node in the linkedListdeleteFirst() {this.head = this.head.nextthis.size--}// return the length of the linkedListlength() {return this.size}}
About we have create the main classes for the Linked list and have also completed all required methods. Now lets initialize this linked list.
</ >const l = new LinkedList()for (let i = 0; i < 10; i++) {l.insert(i) // 0 1 2 3 4 5 6 7 8 9}console.log("Print the linkedList")l.print() // 0 1 2 3 4 5 6 7 8 9l.deleteLast() // 0 1 2 3 4 5 6 7 8l.deleteFirst() // 1 2 3 4 5 6 7 8console.log("Print the linkedList After deleting last and first node")l.print() // 1 2 3 4 5 6 7 8 10l.append(10) // 1 2 3 4 5 6 7 8 10console.log(l.length()) //9
Output:
$ node linkedList.js Print the linkedList 9 8 7 6 5 4 3 2 1 0 Print the linkedList After deleting last and first node 8 7 6 5 4 3 2 1 9
And that is how you can implement linked list in javascript. If you want to see the linked list representation of Stack then click here and how to make stack with array click here.
Thank you ☺
Comments
Post a Comment