From 2917871b5842d0307d4b3ee9609435949058a524 Mon Sep 17 00:00:00 2001 From: = <--gbloal> Date: Wed, 15 May 2024 14:15:14 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E9=93=BE=E8=A1=A8?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E7=BB=93=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- list/README.md | 4 ++++ list/index.js | 1 + list/link-list.js | 60 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 list/README.md create mode 100644 list/index.js create mode 100644 list/link-list.js diff --git a/list/README.md b/list/README.md new file mode 100644 index 0000000..fdb710a --- /dev/null +++ b/list/README.md @@ -0,0 +1,4 @@ +# 链表 +这个目录存放的是列表相关的数据结构 + +# 对应题目 diff --git a/list/index.js b/list/index.js new file mode 100644 index 0000000..5f2152f --- /dev/null +++ b/list/index.js @@ -0,0 +1 @@ +export * from './link-list.js' \ No newline at end of file diff --git a/list/link-list.js b/list/link-list.js new file mode 100644 index 0000000..bc2ecc9 --- /dev/null +++ b/list/link-list.js @@ -0,0 +1,60 @@ +/** + * 单向链表 + * @class LinkList + */ +export class LinkList { + /** + * + * @param {LinkListNode} head - 链表的头节点 + */ + constructor(head){ + this.head = head + } + + /** + * @description 把数组转换成链表,如:[1,2,3] => 1->2->3 + * @param {any[]} array - 要转换的数组 + * @returns { LinkList } 按数组顺序返回的链表 + */ + static fromArray(array){ + let n = array.length + const head = new LinkListNode(array[0]) + const linkList = new LinkList(head) + let curNode = head + for(let i=1;i2->3 + */ + toString(){ + let cur = this.head || this // 兼容节点自身遍历 + let tmpArr = [] + while(cur){ + tmpArr.push(cur.val) + cur = cur.next + } + return tmpArr.join('->') + } +} + +/** + * 单向链表节点 + * @class LinkListNode + */ +export class LinkListNode { + /** + * + * @description 创建一个节点实例 + * @param {any} val - 当前节点保存的值 + * @param {LinkListNode} next - 当前节点下一个节点,默认为空 + */ + constructor(val, next = null){ + this.val = val + this.next = next + } +}