/** * 单向链表 * @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 } }