链表

这里写图片描述

这里写图片描述

这里写图片描述

1.创建一个单节点:

var firstNode = {
    data : 12,
    next : null
};

2.通过第一个单节点的next属性可以链接到另一个单节点从而构成一个链表。

firstNode.next = {
    data : 24,
    next : null
};

//也就是
var LinkedList = {
    data : 12,
    next : {
        data : 24,
        next : null
    }
};

3.接下来可以为链表添加一些方法,如:在原链表最后加入一个新的节点,去掉原链表中的某个节点等等。

function LinkedList(){
    this.length = 0;
    this.head = null;
}
LinkedList.prototype = {
    add: function(data){
        var node = {
            data: data,
            next : null
        };
        //特殊情况,原链表为空
        if(!this.head){
            this.head = node;
        }else{
            current = this.head;
            while(current.next){
                current = current.next;
            }
            current.next = node;
        }
        this.length++;
    },
    item: function(index){
        if(index > -1 && index < this.length){
            var current = this.head,
                i = 0;
            while(i++ < index){
                current = current.next;
            }
            return current.data;
        }else{
            return null;
        }
    },
    remove: function(index){
        if(index > -1 && index < this.length){
            var current = this.head,
                previous,
                i = 0;
            //特殊情况:想要移除为首节点
            if(index === 0){
                this.head = current.next;
            }else{
                while(i++ < index){
                    previous = current;
                    current = current.next;
                }
                previous.next = current.next;
            }
            this.length--;
            return current.data;
        }else{
            return null;
        }
    }
}

参考:
1.Computer science in JavaScript: Linked list
https://www.nczonline.net/blog/2009/04/13/computer-science-in-javascript-linked-list/

2.What is the ‘head’ of a linked list?
https://stackoverflow.com/questions/4973713/what-is-the-head-of-a-linked-list

3.JavaScript 版数据结构与算法(三)链表
https://lewis617.github.io/2017/02/15/linked-list/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值