Last active
April 15, 2017 18:02
-
-
Save brianxautumn/f2cfa793ada7e12a18b6aa5fb605b25d to your computer and use it in GitHub Desktop.
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 SingleLinkedList{ | |
constructor(){ | |
this.firstNode = null; | |
} | |
//Insert item at beginning of list | |
insert(data){ | |
var newNode = new Node(data); | |
newNode.nextNode = this.firstNode; | |
this.firstNode = newNode; | |
} | |
//get Item at index | |
itemAtIndex(index){ | |
var currentIndex = 0; | |
var currentNode = this.firstNode; | |
while(currentIndex !== index){ | |
currentIndex++; | |
if(currentNode.nextNode === null) | |
return null; | |
else | |
currentNode = currentNode.nextNode; | |
} | |
return currentNode.data; | |
} | |
//delete item at index | |
delete(index){ | |
if(index === 0){ | |
this.deleteFirst(); | |
return null; | |
} | |
var currentIndex = 0; | |
var nodeBefore; | |
var currentNode = this.firstNode; | |
while(currentIndex !== index){ | |
currentIndex++; | |
if(currentNode.nextNode === null) | |
return; | |
nodeBefore = currentNode; | |
currentNode = currentNode.nextNode; | |
} | |
nodeBefore.nextNode = currentNode.nextNode; | |
} | |
deleteFirst(){ | |
this.firstNode = this.firstNode.nextNode; | |
} | |
} | |
class Node{ | |
constructor(data){ | |
this.data = data; | |
this.nextNode = null; | |
} | |
} | |
//TEST | |
var list = new SingleLinkedList(); | |
list.insert("hello"); | |
list.insert("how are you"); | |
console.log(list.delete(1)); | |
console.log(list); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment