概念
链表存储有序的元素集合,但不同于数组,链表中的元素在内存中并不是连续放置的。每个元素由一个存储元素本身的节点和一个指向下一个元素的引用(也称指针或链接)组成。
优点:添加或移除元素的时候不需要移动其他元素
缺点:想要查找元素时,要从表头开始进行迭代查找
单链表
function LinkedList() {function Node(element) {this.element = element;this.next = null;}let length = 0;let head = null;// 添加元素this.append = function (element) {let node = new Node(element);let current;if (head === null) {head = node;} else {current = head;while (current.next) {current = current.next;}current.next = node;}length++;};// 移除特定位置的元素this.removeAt = function (position) {if (position > -1 && position < length) {let current = head;let previous, index = 0;if (position === 0) {head = current.next;} else {// 找到指定位置的元素while (index++ < position) {previous = current;current = current.next;}previous.next = current.next;}length--;return current.element;} else {return null;}};// 在指定位置插入元素this.insert = function (position, element) {if (position >= 0 && position <= length) {let node = new Node(element);let current = head;let previous, index = 0;if (position === 0) {node.next = current;head = node;} else {// 找到指定位置的元素while (index++ < position) {previous = current;current = current.next;}node.next = current;previous.next = node;}length++;return true;} else {return false;}};// 将 LinkedList 对象转换为字符串this.toString = function () {let current = head;let string = '';while (current) {string += current.element + '';current = current.next;}return string;};// 返回指定元素的索引this.indexOf = function (element) {let current = head;let index = 0;while (current) {if (current.element === element) {return index;}index++;current = current.next;}return -1;};// 移除指定元素this.remove = function (element) {let index = this.indexOf(element);return this.removeAt(index);};// 链表是否为空this.isEmpty = function () {return length === 0;};// 链表大小this.size = function () {return length;};// 返回链表头this.getHead = function () {return head;};}
