链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。 相比于线性表顺序结构,操作复杂。由于不必须按顺序存储,链表在插入的时候可以达到O(1)的复杂度,比另一种线性表顺序表快得多,但是查找一个节点或者访问特定编号的节点则需要O(n)的时间,而线性表和顺序表相应的时间复杂度分别是O(logn)和O(1)。
使用链表结构可以克服数组链表需要预先知道数据大小的缺点,链表结构可以充分利用计算机内存空间,实现灵活的内存动态管理。但是链表失去了数组随机读取的优点,同时链表由于增加了结点的指针域,空间开销比较大。链表最明显的好处就是,常规数组排列关联项目的方式可能不同于这些数据项目在记忆体或磁盘上顺序,数据的存取往往要在不同的排列顺序中转换。链表允许插入和移除表上任意位置上的节点,但是不允许随机存取。链表有很多种不同的类型:单向链表,双向链表以及循环链表。链表可以在多种编程语言中实现。像Lisp和Scheme这样的语言的内建数据类型中就包含了链表的存取和操作。程序语言或面向对象语言,如C,C++和Java依靠易变工具来生成链表。
单向链表
JS:
链表节点
class Node {constructor(element) {this.element = element;this.next = null;}}
链表
class LinkedList {constructor() {this.head = null;this.length = 0;}
追加元素
append(element) {let node = new Node(element);let current = null;if (!this.head) {// 添加头节点this.head = node;} else {current = this.head;while(current.next) {current = current.next;}current.next = node;}this.length++;}
添加元素
insert(position, element) {if (position >= 0 && position <= this.length) {let node = new Node(element);let previous = null;let index = 0;if (position === 0) {this.head = node;} else {while (index++ < position) {previous = current;current = current.next;}previous.next = node;node.next = current;}this.length++;return true;}return false;}
删除指定位置元素
removeAt(position) {if (position >= 0 && position <= this.length) {let previous = null;let index = 0;if (position === 0) {this.head = current.next;} else {while(index++ < position) {previous = current;current = current.next;}previous.next = current.next;}this.length--;return true;}return false;}
寻找下标元素
findIndex(element) {let current = this.head;let index = -1;while (current.next) {if (current === element) {return index + 1;}current = current.next;index++;}return -1;}
删除指定文档
remove(element) {let index = this.findIndex(element);return this.removeAt(index);}
判断是否为空
isEmpty() {return !this.length;}
返回大小
size() {return this.length;}
判断是否有环
checkAround(list) {// 第一种方法, 创建哈希表,不过会占用较大的空间,不是最佳方法.( 时间复杂度O(n) )function func1() {const set = new Set();while (list) {if (set.has(list)) {console.log("存在环");console.log(list);return true;}list = list.next;}return false;}// 第二种方法: 给节点添加visited访问标记 (时间复杂度O(n)), 不需要额外的空间function func2() {while(list) {if (list.visited) {console.log("存在环");console.log(list);return list;}list.visited = 1;list = list.next;}return false;}// 第三种方法:快慢指针法,设定快指针fast,慢指针slow,每次循环快指针fast移动两个位置,慢指针移动一个位置function func3() {const fast = list.next.next;const slow = list.next;while(list) {if (fast === slow) {console.log("存在环");console.log(list);return true;}fast = fast.next.next;slow = slow.next;}return false;}}
