链表,存储的是有序的元素集合,但不同于数组,链表中的元素在内存中并不是连续放置的。每个元素由一个存储元素本身的节点和一个指向下一个元素的引用(也称指针或链接)组成。如下图展示了一个链表的结构。

class LinkedList {constructor() {this.count = 0;this.head = null;}equalsFn(a, b) {return a === b;}nodeFactory(element) {return {element,next: null}}push(element) {const node = this.nodeFactory(element);if (this.head) {let current = this.head;while (current.next) {current = current.next;}current.next = node;} else {this.head = node;}this.count++;}removeAt(index) {if (index < 0 || index > this.count) {return;}let current = this.head;if (index === 0) {this.head = current.next;} else {let previous = this.getElementAt(index - 1);current = previous.next;previous.next = current.next;}this.count--;return current.element;}insert(element, index) {if (index < 0 || index > this.count) {return;}let node = this.nodeFactory(element);if (index === 0) {node.next = this.head;this.head = element;} else {let previous = this.getElementAt(index - 1);let current = previous.next;node.next = current;previous.next = node;}this.count++;return true;}indexOf(element) {let current = this.head;for (let i = 0; i < this.count; i++) {if (this.equalsFn(element, current.element)) {return i;}current = current.next;}return -1;}remove(element) {let index = this.indexOf(element);return this.removeAt(index);}size() {return this.count;}isEmpty() {return this.size() === 0;}getHead() {return this.head;}getElementAt(index) {if (index < 0 || index > this.count) {return;}let current = this.head;for (let i = 0; i < index; i++) {current = current.next;}return current;}toString() {if (!this.head) return '';let str = `${this.head.element}`;let current = this.head.next;for (let i = 1; i < this.count; i++) {str += `, ${current.element}`;current = current.next;}return str;}}
