快速导航×

JS数据结构实现_链表与二叉树2025-11-16 16:44:56
链表和二叉搜索树可用J*aScript通过对象引用实现。1. 单向链表支持尾插、指定位置插入和删除节点,操作高效;2. 二叉搜索树实现插入、查找、中序遍历及最值获取,平均时间复杂度O(log n)。两者均适用于动态数据管理,是前端算法基础。

js数据结构实现_链表与二叉树

链表和二叉树是前端开发中常被忽视但非常重要的基础数据结构。虽然J*aScript不像C或J*a那样直接支持指针和类,但我们可以通过对象引用来模拟这些结构。下面介绍如何用JS实现单向链表和二叉搜索树(BST),并附上常用操作。

单向链表的实现

链表由一系列节点组成,每个节点包含数据和指向下一个节点的引用。相比数组,链表在插入和删除操作上更高效。

定义节点和链表结构:

class ListNode {
  constructor(val) {
    this.val = val;
    this.next = null;
  }
}
<p>class LinkedList {
constructor() {
this.head = null;
this.size = 0;
}</p><p>// 在尾部添加节点
append(val) {
const node = new ListNode(val);
if (!this.head) {
this.head = node;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
this.size++;
}</p><p>// 在指定位置插入
insertAt(index, val) {
if (index < 0 || index > this.size) return false;
const node = new ListNode(val);
if (index === 0) {
node.next = this.head;
this.head = node;
} else {
let current = this.head;
for (let i = 0; i < index - 1; i++) {
current = current.next;
}
node.next = current.next;
current.next = node;
}
this.size++;
return true;
}</p><p>// 删除指定值的第一个节点
remove(val) {
if (!this.head) return null;
if (this.head.val === val) {
const removed = this.head;
this.head = this.head.next;
this.size--;
return removed.val;
}
let current = this.head;
while (current.next && current.next.val !== val) {
current = current.next;
}
if (current.next) {
const removed = current.next;
current.next = current.next.next;
this.size--;
return removed.val;
}
return null;
}</p><p>// 打印链表
print() {
const result = [];
let current = this.head;
while (current) {
result.push(current.val);
current = current.next;
}
console.log(result.join(' -> '));
}
}</p>

使用示例:

const list = new LinkedList();
list.append(1);
list.append(2);
list.append(3);
list.insertAt(1, 1.5);
list.print(); // 输出: 1 -> 1.5 -> 2 -> 3
list.remove(1.5);
list.print(); // 输出: 1 -> 2 -> 3
</font><H3>二叉搜索树(BST)的实现</H3><p>二叉树每个节点最多有两个子节点:左子树和右子树。二叉搜索树在此基础上满足:左子节点值小于父节点,右子节点值大于父节点。</p>
                    <div class="aritcle_card">
                        <a class="aritcle_card_img" href="/ai/1728">
                            <img src="https://img.php.cn/upload/ai_manual/000/969/633/68b6d28da274e764.png" alt="Visla">
                        </a>
                        <div class="aritcle_card_info">
                            <a href="/ai/1728">Visla</a>
                            <p>AI视频生成器,快速轻松地将您的想法转化为视觉上令人惊叹的视频。</p>
                            <div class="">
                                <img src="/static/images/card_xiazai.png" alt="Visla">
                                <span>100</span>
                            </div>
                        </div>
                        <a href="/ai/1728" class="aritcle_card_btn">
                            <span>查看详情</span>
                            <img src="/static/images/cardxiayige-3.png" alt="Visla">
                        </a>
                    </div>
                <p><strong>定义节点和树结构:</strong></p><font color="#0000FF"><pre class="brush:php;toolbar:false;">
class TreeNode {
  constructor(val) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}
<p>class BinarySearchTree {
constructor() {
this.root = null;
}</p><p>// 插入节点
insert(val) {
const node = new TreeNode(val);
if (!this.root) {
this.root = node;
} else {
this._insertNode(this.root, node);
}
}</p><p>_insertNode(root, node) {
if (node.val < root.val) {
if (!root.left) {
root.left = node;
} else {
this._insertNode(root.left, node);
}
} else {
if (!root.right) {
root.right = node;
} else {
this._insertNode(root.right, node);
}
}
}</p><p>// 查找节点
search(val) {
return this._searchNode(this.root, val);
}</p><p>_searchNode(root, val) {
if (!root) return false;
if (val === root.val) return true;
return val < root.val 
? this._searchNode(root.left, val)
: this._searchNode(root.right, val);
}</p><p>// 中序遍历(升序输出)
inOrder(callback) {
this._inOrderNode(this.root, callback);
}</p><p>_inOrderNode(node, callback) {
if (node) {
this._inOrderNode(node.left, callback);
callback(node.val);
this._inOrderNode(node.right, callback);
}
}</p><p>// 最小值
min() {
let node = this.root;
while (node && node.left) {
node = node.left;
}
return node ? node.val : null;
}</p><p>// 最大值
max() {
let node = this.root;
while (node && node.right) {
node = node.right;
}
return node ? node.val : null;
}
}</p>

使用示例:

const bst = new BinarySearchTree();
bst.insert(10);
bst.insert(5);
bst.insert(15);
bst.insert(3);
bst.insert(7);
<p>console.log(bst.search(7)); // true
console.log(bst.search(12)); // false</p><p>bst.inOrder((val) => console.log(val)); // 输出: 3, 5, 7, 10, 15
console.log(bst.min()); // 3
console.log(bst.max()); // 15</p>

链表适合频繁增删的场景,而二叉搜索树在查找、插入、删除上平均时间复杂度为O(log n),特别适合动态数据集合管理。理解这些结构有助于写出更高效的算法,比如LeetCode中的很多题目都依赖这些基础。

基本上就这些,不复杂但容易忽略细节。掌握后可以尝试扩展双向链表、平衡二叉树等进阶内容。

以上就是JS数据结构实现_链表与二叉树的详细内容,更多请关注其它相关文章!


# 如何用  # seo 黑科技  # 烟台网络营销网络推广平台  # dy刷粉网站推广便宜  # seo网站的优化核心  # 故事会网站建设  # 飞飞cms板块seo  # 不花钱高级seo技巧  # 阜宁seo公司报价  # 鲜花培训网站建设  # 抚州南城网站建设  # 复选框  # 服务端  # 多线程  # 遍历  # js数据结构  # 如何实现  # 二叉树  # 子树  # 数据结构  # 链表  # 前端开发  # app  # node  # 前端  # js  # java  # javascript  # 链表二叉树 


相关栏目: 【 企业资讯168 】 【 行业动态20933 】 【 网络营销52431 】 【 网络学院91036 】 【 运营推广7012 】 【 科技资讯60970


相关推荐: J*aScript中高效管理与清空动态列表:避免循环陷阱  React Hooks最佳实践:动态组件状态管理的组件化方案  如何在CSS中使用浮动制作导航栏_float实现水平菜单  怎样使用“本地安全策略”提升Windows安全性_Secpol.msc配置指南【高手】  Golang指针如何与map组合使用_Golang map指针组合实践  合作发布豆包手机助手工程样机 中兴通讯封涨停  Win11怎么查看显卡显存 Win11显示适配器属性及专用视频内存查询  Win11如何使用Windows Sandbox Win11沙盒功能开启与使用教程【详解】  Golang如何使用const iota_Go iota常量计数器讲解  Golang如何使用bytes.Split分割字节切片_Golang bytes切片分割方法  在J*a中如何实现简单的用户输入_J*aScanner类使用方法分享  Golang如何测试channel通信行为_Golang channel通信测试与分析方法  Win10磁盘清理工具在哪 Win10打开并使用磁盘清理【教程】  qq音乐在线播放入口_qq音乐电脑版登录链接  大象笔记网页版入口 印象笔记网页版登录入口  uc手机浏览器网页版入口 uc浏览器手机版便捷登录首页  怎样在Excel中做仪表盘_Excel仪表盘设计与关键指标展示方法  如何使用spryker/configurable-bundles-products-resource-relationship模块解决复杂产品捆绑关系难题  Win11怎么开启高性能模式_Windows 11电源计划优化设置  必由学网页版入口 必由学官方平台直接访问  12306选座系统怎么选连座_12306选座多人连坐操作方法  怎样把文件彻底粉碎无法恢复_Windows下安全删除敏感数据【隐私保护】  高德地图怎么看全景照片_高德地图全景照片浏览教程  迅雷下载到U盘速度很慢怎么办_迅雷U盘下载慢优化方法  蛙漫官网漫画入口地址_蛙漫在线畅读无广告弹窗  Win11网速慢怎么解决 Win11网络设置优化解除限速  C++编译期如何执行复杂计算_C++模板元编程(TMP)技巧与应用  照顾宝贝2小游戏点击立即在线玩  qq游戏网页版直接玩_qq游戏免下载快速入口  Basecamp怎样用留言钉固定重点_Basecamp用留言钉固定重点【重点标记】  Yandex官方入口网址 Yandex俄罗斯搜索引擎最新在线地址  html网页设计源代码怎么运行_运行html网页设计源代码步骤【指南】  抖音怎么赚钱_抖音创作者变现方法与途径指南  谷歌邮箱注册显示错误Gmail服务器异常与延迟处理  QQ邮箱网页版快速登录 QQ邮箱邮箱账号官方入口地址  win11 arm版怎么安装 M1/M2 Mac虚拟机安装ARM win11的方法  Python中高效访问嵌套字典与列表中的键值对  C++ string清空内容_C++ clear与empty用法  护手霜蹭到袖口上了如何清洗? 怎样避免留下一圈油印?  腾讯QQ邮箱登录入口_QQ邮箱官方网站使用地址  深入理解J*a合成构造器:何时以及为何阻止其生成  将HTML动态表格多行数据保存到Google Sheet的教程  德邦快递查询平台 德邦快递物流信息查询入口  如何将HTML表格多行数据保存到Google Sheets  三星GalaxyZFold5怎样在相册制作折叠屏分镜_iPhone三星GalaxyZFold5相册制作折叠屏分镜【创意编辑】  2026年发布! 美少女养成动作RPG《神剑少女战记》发布实机演示  VS Code初学者必知的10个基本操作  动漫共和国防屏蔽稳定域名-动漫共和国官方正版直达通道  J*aScript数组对象转换:按指定键分组与值收集  京东京造J1和网易云音乐氧气真无线有什么不同_国产电商蓝牙耳机音质对比