Skip to content

Instantly share code, notes, and snippets.

@brianxautumn
Last active April 15, 2017 18:02
Show Gist options
  • Save brianxautumn/f2cfa793ada7e12a18b6aa5fb605b25d to your computer and use it in GitHub Desktop.
Save brianxautumn/f2cfa793ada7e12a18b6aa5fb605b25d to your computer and use it in GitHub Desktop.
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