码迷,mamicode.com
首页 > 其他好文 > 详细

双向链表

时间:2017-05-21 17:52:17      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:nbsp   http   each   技术   查找   tail   pre   str   log   

双向链表的结构

技术分享

双向链表的节点

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;
    }
}

 

双向链表

标签:nbsp   http   each   技术   查找   tail   pre   str   log   

原文地址:http://www.cnblogs.com/mengff/p/6885320.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!