美文网首页
数据结构 - 链表

数据结构 - 链表

作者: Top_Chenxi | 来源:发表于2017-04-22 15:13 被阅读3次
    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;
    

    相关文章

      网友评论

          本文标题:数据结构 - 链表

          本文链接:https://www.haomeiwen.com/subject/yxyszttx.html