js 单链表

单链表

function Node(element){
    this.element = element;//当前节点数据
    this.next =  null;//下一节点数据
}

function LList(){
    this.head = new Node('head')
}
LList.prototype  =  {
    find:function(item){
        var currNode = this.head;
        while(currNode.element != item){
            currNode =  currNode.next;
        }
        return currNode;
    },
    insert:function(newElement,item){
        var newNode =  new Node(newElement);
        var current =  this.find(item);
        newNode.next = current.next;
        current.next = newNode;
    },
    findPrevious:function(item){
        var currNode = this.head;
        while(!(currNode.next == null) && (currNode.next.element != item)){
            currNode =  currNode.next;
        }
        return currNode;
    },
    remove:function(item){
        var preNode = this.findPrevious(item);
        if(!(preNode.next == null)){
            preNode.next = preNode.next.next
        }
    },
    edit:function(item,newItem){
        var element =  this.find(item);
        element.element = newItem;
    },
    display:function(){
        var currNode = this.head;
        while(!(currNode.next  == null)){
            // console.log(currNode.next.element);
            currNode = currNode.next;
        }
    }
}
var names = new LList();
names.insert('add','head');
names.insert('delete','add')
console.log(names.find('delete'));

你可能感兴趣的:(js 单链表)