feat: 添加链表数据结构
This commit is contained in:
parent
8f8cd44f85
commit
2917871b58
4
list/README.md
Normal file
4
list/README.md
Normal file
@ -0,0 +1,4 @@
|
||||
# 链表
|
||||
这个目录存放的是列表相关的数据结构
|
||||
|
||||
# 对应题目
|
1
list/index.js
Normal file
1
list/index.js
Normal file
@ -0,0 +1 @@
|
||||
export * from './link-list.js'
|
60
list/link-list.js
Normal file
60
list/link-list.js
Normal file
@ -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;i<n;i++){
|
||||
curNode.next = new LinkListNode(array[i])
|
||||
curNode = curNode.next
|
||||
}
|
||||
return linkList
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 返回序列化之后的链表 1->2->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
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user