JS版数据结构-链表
链表代码随笔(JS)
/** 链表节点 */ class Node { el = null; next = null; constructor(el = null, next = null) { this.el = el; this.next = next; } } /** 链表 */ class LinkedList { #dummy = null; #size = 0; constructor() { this.#dummy = new Node(); } getSize() { return this.#size; } isEmpty() { return this.#size === 0; } insert(idx, el) { if (idx < 0 || idx > this.#size) { throw new Error('Out of bounds!'); } let prev = this.#dummy; for (let i = 0; i < idx; i++) { prev = prev.next; } prev.next = new Node(el, prev.next); this.#size++; } addFirst(el) { this.insert(0, el); } addLast(el) { this.insert(this.#size, el); } get(idx) { if (idx < 0 || idx >= this.#size) { throw new Error('Out of bounds!'); } let cur = this.#dummy.next; for (let i = 0; i < idx; i++) { cur = cur.next; } return cur.el; } getFirst() { return this.get(0); } getLast() { return this.get(this.#size - 1); } set(idx, el) { if (idx < 0 || idx >= this.#size) { throw new Error('Out of bounds!'); } let cur = this.#dummy.next; for (let i = 0; i < idx; i++) { cur = cur.next; } cur.el = el; } removeByIndex(idx) { if (idx < 0 || idx >= this.#size) { throw new Error('Out of bounds!'); } let prev = this.#dummy; for (let i = 0; i < idx; i++) { prev = prev.next; } const target = prev.next; prev.next = target.next; target.next = null; this.#size--; return target; } contains(el) { let cur = this.#dummy.next; while (cur !== null) { if (cur.el === el) { return true; } cur = cur.next; } return false; } print() { let cur = this.#dummy; console.info('start: ' ); while (cur !== null) { console.log(cur.el); cur = cur.next; } console.info('end!'); } } const linkedList = new LinkedList(); linkedList.addLast(new Node(1)) linkedList.addLast(new Node(2)) linkedList.print();
分类:
JavaScript
, 数据结构与算法
标签:
JavaScript
, 数据结构与算法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?