var LinkedList = function() {
this.Node = function(element) {
this.element = element;
this.next = null;
};
this.head = new this.Node('head');
};
LinkedList.prototype.find = function(item) {
var currNode = this.head;
while (currNode.element !== item) {
currNode = currNode.next;
}
return currNode;
};
LinkedList.prototype.insert = function(element, previous) {
var newNode = new this.Node(element),
prev = this.find(previous);
newNode.next = prev.next;
prev.next = newNode;
};
LinkedList.prototype.seeAll = function() {
var currNode = this.head,
contents = [];
while (currNode.next !== null) {
contents.push(currNode.next.element);
currNode = currNode.next;
}
return contents;
};
LinkedList.prototype.findPrevious = function(item) {
var currNode = this.head;
while (currNode.next !== null && currNode.next.element !== item) {
currNode = currNode.next;
}
return currNode;
};
LinkedList.prototype.remove = function(item) {
var prevNode = this.findPrevious(item);
if (prevNode.next !== null) {
prevNode.next = prevNode.next.next;
}
};
module.exports = LinkedList;
网友评论