js数据结构之链表

本文详细探讨了JavaScript中的链表数据结构,包括其基本概念、操作以及在实际编程中的应用。通过学习,读者将能够掌握链表的插入、删除和遍历等核心操作,并了解链表相对于数组的优势。

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

//定义节点
function ListNode(val) {
    this.val = val;
    this.next = null;
}

//定义链表
//链表中有头结点和一些方法
function LinkedList() {
    this.head = new ListNode('head');
    this.find = find;
    this.insert = insert;
    this.remove = remove;
    this.show = show;
    this.findFront = findFront;
}

//定义一些方法
//查找节点
function find(item) {
    var curNode = this.head;
    while (curNode.val != item) {
        curNode = curNode.next;
    }
    return curNode; //找到就返回结点数据,没有就返回null
}

//插入节点
function insert(newElement, item) {
    //插入的节点,和位置
    var newNode = new ListNode(newElement);
    var curNode = this.find(item);
    var nextNode = curNode.next;
    // newNode.next = curNode.next;
    curNode.next = newNode;
    newNode.next = nextNode;
}
//找到前节点
function findFront(item) {
    var curNode = this.head;
    if (curNode.next.val != item) {
        curNode = curNode.next;
    }
    return curNode;
}
//删除节点
function remove(item) {
    var frontNode = this.findFront(item);
    var curNode = this.find(item);
    frontNode.next = curNode.next;

}
//遍历节点
function show() {
    var curNode = this.head,
        result = '';
    while (curNode.next != null) {
        result += curNode.next.val;
        curNode = curNode.next;
    }
    return result;

}

测试

    var list = new LinkedList();
    list.insert('a', 'head')
    list.insert('b', 'a')
    list.insert('c', 'b')
    console.log(list.show())
    list.remove('a')
    console.log(list.show())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值