js 双向链表 插入 查找

本文详细介绍了如何在JavaScript中实现双向链表数据结构,包括节点的创建、链表的初始化,以及核心的插入和查找操作。通过实例代码解析,帮助读者深入理解双向链表的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


function Node(value) {
    this.value = value;
    this.prev = null;
    this.next = null;
    return this;
}

function List() {
    this.head = new Node(null);
    this.insert = function(index, node) {
        let pNode = this.find(index);
        let nNode = pNode.next;
        pNode.next = node;
        node.next = nNode;
        node.prev = pNode;
        nNode.prev = node;
    }
    this.find = function(index) {
        let node = this.head;
        while(--index) {
            node = node.next
        }
        return node;
    }
    this.append = function(node) {
        let lastNode = this.head
        while(lastNode.next != null ) {
            lastNode = lastNode.next
        }
        node.prev = lastNode
        lastNode.next = node;
        
    }

    return this;
}

let list = new List();
let N1 = new Node(1);
let N2 = new Node(2);
let N3 = new Node(3);
let N4 = new Node(4);
let N5 = new Node(5);
let N6 = new Node(6);

list.append(N1);
list.append(N2);
list.append(N3);
list.append(N4);
list.append(N5);
list.append(N6);

list.insert(1,new Node(7))

console.log(list.find(2))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值