首页 > 代码库 > 双向链表

双向链表

双向链表的结构

技术分享

双向链表的节点

function Node(val){
    this.val = val;
    this.next = null;
    this.pre = null;
}

双向链表的创建

尾插法

function tailCreateList(arr){
    var head = new Node();
    var pre = head;
    arr.forEach((item) => {
        var node = new Node(item);
        node.pre = pre;
        pre.next = node;
        pre = pre.next;
    })
}

头插法

function headCreateList(arr){
    var head = new Node();
    var cur = head;
    arr.forEach((item) => {
        var node = new Node(item);
        node.pre = head;
        node.next = head.next;
        if(head.next){
            head.next.pre = node;
        }
        head.next = node;
    })
    return head;
}

双链表的遍历

function traverse(head,fVisit){
    var cur = head;
    fVisit = fVisit || function(item){console.log(item)}
    while(cur != null){
        fVisit(cur);
        cur = cur.next;
    }
}

双链表的查找

function find(head,val){
    var cur = head;
    while(cur && cur.val != val){
        cur = cur.next;
    }
    return cur;
}

双链表的删除

function remove(head,val){
    var cur = head;
    while(cur && cur.val != val){
        cur = cur.next;
    }
    if(cur != null){
        cur.pre.next = cur.next;
        cur.next.pre = cur.pre;
        cur.next = null;
        cur.pre = null;
    }
}

双链表的插入

function insert(head,val,newVal){
    var cur = head;
    while(cur && cur.val != val){
        cur = cur.next;
    }
    if(cur != null){
        var node = new Node(newVal);
        node.next = cur.next;
        node.pre = cur;
        cur.next = node;
    }
}

 

双向链表