Skip to content

Instantly share code, notes, and snippets.

@robabby
Created November 8, 2015 00:56
Show Gist options
  • Save robabby/43867098aec4e4181d50 to your computer and use it in GitHub Desktop.
Save robabby/43867098aec4e4181d50 to your computer and use it in GitHub Desktop.
function LinkedList() {
var Node = function(element) {
this.element = element;
this.next = null;
};
var length = 0;
var head = null;
this.append = function(element) {
var node = new Node(element),
current;
if(head === null) {
head = node;
} else {
current = head;
// loop the list until we find the last item
while(current.next) {
current = current.next;
}
// get the last item and assign next to node to make the LinkedList
current.next = node;
}
length++;
};
this.insert = function(position, element) {
// check for out-of-bounds values
if (position >= 0 && position <= length) {
var node = new Node(element),
current = head,
previous,
index = 0;
if (position === 0) {
node.next = current;
head = node;
} else {
while (index++ < position) {
previous = current;
current = current.next;
}
node.next = current;
previous.next = node;
}
length++;
return true;
} else {
return false;
}
};
this.removeAt = function(element) {
// check for out-of-bounds values
if (position > -1 && position < length) {
var current = head,
previous,
index = 0;
// removing the first item
if (position === 0) {
head = current.next;
} else {
while (index++ < position) {
previous = current;
current = current.next;
}
// link previous with /current/s next: skip it to remove
previous.next = current.next;
}
length--;
return current.element;
} else {
return null;
}
};
this.remove = function(element) {
var index = this.indexOf(element);
return this.removeAt(index);
};
this.indexOf = function(element) {
var current = head,
index = -1;
while (current) {
if (element === current.element) {
return index;
}
index++;
current = current.next;
}
return -1;
};
this.isEmpty = function() {
return length === 0;
};
this.size = function() {
return length;
};
this.toString = function() {
var current = head,
string = '';
while (current) {
string = current.element;
current = current.next;
}
return string;
};
this.getHead = function() {
return head;
};
this.print = function() {
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment