61 lines
1.3 KiB
JavaScript
61 lines
1.3 KiB
JavaScript
/**
|
|
* 单向链表
|
|
* @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) {
|
|
const 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; // 兼容节点自身遍历
|
|
const 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;
|
|
}
|
|
}
|