Skip to content

Instantly share code, notes, and snippets.

@andrewsouthard1
Last active July 24, 2017 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewsouthard1/fe585bb0dd99192d68806e00ca289ed6 to your computer and use it in GitHub Desktop.
Save andrewsouthard1/fe585bb0dd99192d68806e00ca289ed6 to your computer and use it in GitHub Desktop.
Linked List
function LinkedList() {
head = null;
length = 0;
var Node = function(element) {
this.element = element;
this.next = null;
}
this.head = function() {
return head;
}
this.length = function() {
return length;
}
this.add = function(element) {
var newNode = new Node(element);
if(head === null) {
head = newNode;
} else {
var currentNode = head;
while(currentNode.next !== null) {
currentNode = currentNode.next;
}
currentNode.next = newNode;
}
length++;
}
this.remove = function(element){
if(head === null) {
return “empty linked list, nothing to remove”;
} else {
var currentNode = head;
if(currentNode.element === element){
head = currentNode.next;
length--;
return head;
} else {
while(currentNode.next !== null) {
if(currentNode.next.element === element){
currentNode.next = currentNode.next.next;
length--;
return head;
}
currentNode = currentNode.next;
}
}
}
}
this.find = function(element) {
currentNode = head;
position = 1;
if(head === null){
return "empty linked linked list";
}
else {
if (currentNode.element === element) {
return position;
} else {
while(currentNode.element !== element){
currentNode = currentNode.next;
position++;
}
if (currentNode.element === element){
return position;
} else {
console.log("this hits");
return -1;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment