Last active
October 10, 2021 01:05
-
-
Save white-hat-vaibhs/c53520ce9c367af87a5bd556034a96a1 to your computer and use it in GitHub Desktop.
JS LinkedList
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor(data, next = null) { | |
this.data = data; | |
this.next = next; | |
} | |
} | |
class LinkedList { | |
constructor() { | |
this.head = null; | |
this.size = 0; | |
} | |
// Insert at the beginning of the list | |
insertAtBeginning(data) { | |
this.head = new Node(data, this.head); | |
this.size++; | |
} | |
//Insert at the end of the list | |
insertLast(data){ | |
let node = new Node(data); | |
let current; | |
if(this.head === null){ | |
this.head = node; | |
} | |
else{ | |
current = this.head; | |
while(current.next){ | |
current = current.next; | |
} | |
current.next = node; | |
} | |
this.size++; | |
} | |
//insert at the index | |
insertAt(data, index) { | |
//if index is out of range | |
if (index > 0 && index > this.size) { | |
return; | |
} | |
if (index === 0) { | |
this.head = new Node(data, this.head); | |
} | |
const node = new Node(data); | |
let current, previous; | |
current = this.head; | |
let count = 0; | |
while (count < index) { | |
previous = current; | |
current = current.next; | |
count++; | |
} | |
} | |
//delete at the index | |
deleteAt(index) { | |
if (index > 0 && index > this.size) { | |
return; | |
} | |
let current = this.head; | |
let previous; | |
let count = 0; | |
if (index === 0) { | |
this.head = current.next; | |
} | |
else { | |
while (count < index) { | |
previous = current; | |
current = current.next; | |
count++; | |
} | |
previous.next = current.next; | |
} | |
this.size--; | |
} | |
//delete at the end of the list | |
deleteLast() { | |
if (!this.head) { | |
return; | |
} | |
let current = this.head; | |
let previous; | |
while (current.next) { | |
previous = current; | |
current = current.next; | |
} | |
previous.next = null; | |
this.size--; | |
} | |
//delete at the index | |
deleteAt(index) { | |
if (index > 0 && index > this.size) { | |
return; | |
} | |
let current = this.head; | |
let previous; | |
let count = 0; | |
if (index === 0) { | |
this.head = current.next; | |
} | |
else { | |
while (count < index) { | |
previous = current; | |
current = current.next; | |
count++; | |
} | |
previous.next = current.next; | |
} | |
this.size--; | |
} | |
//print the linked List | |
printList() { | |
let temp = this.head; | |
while (temp) { | |
console.log(temp.data); | |
temp = temp.next; | |
} | |
} | |
} | |
const ll = new LinkedList(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment