数据结构 - 链表

2017-04-22  本文已影响3人  Top_Chenxi
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;
上一篇下一篇

猜你喜欢

热点阅读