Skip to content

Instantly share code, notes, and snippets.

@voidnerd
Created March 20, 2020 07:18
Show Gist options
  • Save voidnerd/2b29f7df10088a84ba25b4c5dc229d38 to your computer and use it in GitHub Desktop.
Save voidnerd/2b29f7df10088a84ba25b4c5dc229d38 to your computer and use it in GitHub Desktop.
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor () {
this.head = null;
this.size = 0;
}
prepend (data) {
const newHead = new Node(data);
newHead.next = this.head;
this.head = newHead;
this.size++
}
append(data) {
if(this.head == null) {
this.head = new Node(data);
this.size++
return;
}
let currentNode = this.head;
while(currentNode.next != null) {
currentNode = currentNode.next;
}
currentNode.next = new Node(data);
this.size ++
}
deleteValue(data) {
if (this.head == null) return;
if(this.head.data == data) {
this.head = this.head.next;
this.size--;
return;
}
let currentNode = this.head;
while(currentNode.next != null) {
if(currentNode.next.data == data) {
currentNode.next = currentNode.next.next;
this.size--
return data;
}
currentNode = currentNode.next;
}
}
getNth(index) {
if(index < 0 || index >= this.size) {
return;
}
let currentNodeIndex = -1;
let currentNode = this.head;
console.log(this.head.data)
while(currentNodeIndex < index) {
currentNodeIndex++
if(currentNodeIndex === index) {
return currentNode.data;
}
currentNode = currentNode.next;
}
}
indexOf(data) {
let index = -1;
let currentNode = this.head;
while(currentNode) {
index++
if(currentNode.data == data) {
return index;
}
currentNode = currentNode.next
}
}
addAt(index, data){
if(index < 0 || index > this.size) {
return;
}
let currentNode = this.head;
let currentIndex = 0;
let previousNode;
let node = new Node(data);
if(index == 0) {
node.next = currentNode;
this.head = node;
this.size++
}else {
while(currentIndex < index) {
currentIndex++;
previousNode = currentNode;
currentNode = currentNode.next
}
node.next = currentNode;
previousNode.next = node;
this.size++
}
}
removeAt (index) {
let currentNode = this.head;
let previousNode;
let currentIndex = 0;
if(this.head == null) return;
if(index == 0) {
this.head = currentNode.next;
this.size--;
}else {
while(currentIndex < index) {
currentIndex++
previousNode = currentNode;
currentNode = currentNode.next
}
previousNode.next = currentNode.next;
this.size--;
}
}
}
const list = new LinkedList();
list.prepend(400)
list.append(500)
list.addAt(1, 200)
// list.deleteValue(200)
list.removeAt(1);
console.log("nth element:", list.getNth(1))
console.log("index of data:", list.indexOf(500))
console.log(list.size);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment