数据结构与算法JavaScript描述读书笔记(js实现链表-双向链表)

双向链表

双向链表的 remove() 方法比单向链表的效率更高,因为不需要再查找前驱节点了

//创建构造函数创建节点
function Node(element){
    this.element = element;
    this.next = null;
    this.previous = null;
    this.findLast = findLast;
    this.disPreverse = disPreverse;
}
//链表的构造函数
 function LList(){
    this.head = new Node('head');
    this.insert = insert;
    this.remove = remove;
    this.display = display;
    this.find = find;
 }
 function insert(newElement,item){
    var cur = this.find(item);
    var node = new Node(newElement);
    if(cur == null){
        alert('没有找到插入位置');
    }else{
        node.next = cur.next;
        node.previous = cur;
        cur.next = node;
    }
 }
 function find(item){
    var cur = this.head;
    while(cur.element != item){
        cur = cur.next;
    }
    return cur;
 }
 function display() {
     var cur = this.head;
     var str = '';
     while (cur.next != null){
        str += cur.next.element+'->';
        cur = cur.next;
     }
     return str;
 }
 function remove(item){
    var cur = this.find(item);
    if(cur.next != null){
        cur.previous.next = cur.next;
        cur.next.previous = cur.previous;
        cur.next = null;
        cur.previous = null;
    }else{
        //注意,当节点的后继为null时不要设置cur.next.previous = cur.previous
        //因为双向链表中null时没有前驱的,不能设置null的前驱
        cur.previous.next = null;
    }
    
 }
 //查找最后一个节点
function findLast(){
    var cur = this.head;
    while(cur.next != null){
        cur = cur.next;
    }
    return cur;
}
//反序输出节点
function disPreverse(){
    //注意,findLast()即使没有参数也要带括号
    //如果不带括号,last则是一个function对象
    var last = this.findLast();
    //console.log(last);
    var str = '';
    while(last.previous != null){
        str += last.element+'->';
        last = last.previous;
    }
    return str;
}

 

猜你喜欢

转载自blog.csdn.net/qq_37200686/article/details/83111537