js实现链表

链表

加粗样式概念:
链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。

逻辑如下图:
在这里插入图片描述
实现代码如下:

class ArrayLink{
    constructor(){
        this.top = null;
        this.length = 0;
    }
    getValueForIndex(index){
        if(index<0 || index> this.length) return null;
        let cur = this.top
        for(let i = 0; i< index; i++){
            cur = cur.next
        }
        return cur
    }
    getValueForNode(value){
        let cur = this.top
        for(let i = 0; i< this.length; i++){
            if(cur.value === value) return cur;
            cur = cur.next
        }
        return cur
    }
    push(value){
        let newNode = new Node(value)
        let pre = this.top;
        if(this.length === 0){
            this.top = newNode;
            this.length++;
            return;
        }else{
            pre = this.getValueForIndex(this.length-1)
        }
        pre.next = newNode;
        this.length++;
    }
    insert(index, value){
        if(index<0 || index> this.length) return null;
        let newNode = new Node(value)
        const pre = this.getValueForIndex(index-1)
        newNode.next = pre.next;
        pre.next = newNode;
        this.length++;
    }
    remove(value){
        let cur = this.top;
        for(let i = 0; i< this.length-1; i++){
            if(cur.next.value === value){
                cur.next = cur.next.next;
                this.length--;  
            }
            cur = cur.next
        }
    }
    removeAt(index){
        const pre= this.getValueForIndex(index-1)
        pre.next = pre.next.next;
        this.length--;
   
    }
    forEach(){
        let cur = this.top;
        for(let i = 0; i< this.length; i++){
            console.log(cur.value);
            cur = cur.next
        }
    }
}

// 节点
class Node{
    constructor(value){
        this.value = value;
        this.next = null;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值