资讯专栏INFORMATION COLUMN

JS数据结构与算法_链表

NeverSayNever / 1775人阅读

摘要:上一篇数据结构与算法栈队列下一篇数据结构与算法集合字典写在前面说明数据结构与算法系列文章的代码和示例均可在此找到上一篇博客发布以后,仅几天的时间竟然成为了我写博客以来点赞数最多的一篇博客。

上一篇:JS数据结构与算法_栈&队列
下一篇:JS数据结构与算法_集合&字典

写在前面

</>复制代码

  1. 说明:JS数据结构与算法 系列文章的代码和示例均可在此找到

上一篇博客发布以后,仅几天的时间竟然成为了我写博客以来点赞数最多的一篇博客。欢喜之余,不由得思考背后的原因,前端er离数据结构与算法太遥远了,论坛里也少有人去专门为数据结构与算法撰文,才使得这看似平平的文章收获如此。不过,这样也更加坚定了我继续学习数据结构与算法的决心(虽然只是入门级的)

一、链表数据结构

相较于之前学习的 栈/队列 只关心 栈顶/首尾 的模式,链表更加像是数组。链表和数组都是用于存储有序元素的集合,但有几点大不相同

链表不同于数组,链表中的元素在内存中并不是连续放置的

链表添加或移除元素不需要移动其他元素

数组可以直接访问任何一个位置的元素,链表必须从表头开始迭代到指定位置访问

下面是单链表的基本结构

长度为3的单链表

每个元素由一个存储元素本身data的节点和一个指向下一个元素的引用next(也称指针或链接)组成

尾节点的引用next指向为null

类比:寻宝游戏,你有一条线索,这条线索是指向寻找下一条线索的地点的指针。你顺着这条链接去下一个地点,得到另一条指向再下一处的线索。得到列表中间的线索的唯一办法,就是从起点(第一条线索)顺着列表寻找

二、链表的实现

链表的实现不像之前介绍的栈和队列一般依赖于数组(至少我们目前是这样实现的),它必须自己构建类并组织逻辑实现。我们先创建一个Node

</>复制代码

  1. // 节点基类
  2. class Node {
  3. constructor(data) {
  4. this.data = data;
  5. this.next = null;
  6. }
  7. }

一般单链表有以下几种方法:

append 在链表尾部添加一个元素

insert 在指定位置插入元素

removeAt 在指定位置删除元素

getNode 获取指定位置的元素

print 打印整个链表

indexOf 查找链表中是否有某个元素,有则返回索引,没有则返回-1

getHead 获取链表头部

getTail 获取链表尾部(有些并未实现尾部)

size 返回链表包含的元素个数

clear 清空链表

</>复制代码

  1. // 初始化链表
  2. class LinkedList {
  3. constructor() {
  4. this._head = null;
  5. this._tail = null;
  6. this._length = 0;
  7. }
  8. // 方法...
  9. }

下面我们来实现几个重要的方法

2.1 append方法

在链表尾部添加一个新的元素可分为两种情况:

原链表中无元素,添加元素后,headtail均指向新元素

原链表中有元素,更新tail元素(如下)

代码实现

</>复制代码

  1. // 在链表尾端添加元素
  2. append(data) {
  3. const newNode = new Node(data);
  4. if (this._length === 0) {
  5. this._head = newNode;
  6. this._tail = newNode;
  7. } else {
  8. this._tail.next = newNode;
  9. this._tail = newNode;
  10. }
  11. this._length += 1;
  12. return true;
  13. }
2.2 print方法

为方便验证,我们先实现print方法。方法虽简单,这里却涉及到链表遍历精髓

</>复制代码

  1. // 打印链表
  2. print() {
  3. let ret = [];
  4. // 遍历需从链表头部开始
  5. let currNode = this._head;
  6. // 单链表最终指向null,作为结束标志
  7. while (currNode) {
  8. ret.push(currNode.data);
  9. // 轮询至下一节点
  10. currNode = currNode.next;
  11. }
  12. console.log(ret.join(" --> "));
  13. }
  14. // 验证
  15. const link = new LinkedList();
  16. link.append(1);
  17. link.append(2);
  18. link.append(3);
  19. link.print(); // 1 --> 2 --> 3
2.3 getNode方法

获取指定索引位置的节点,依次遍历链表,直到指定位置返回

</>复制代码

  1. // 获取指定位置元素
  2. getNode(index) {
  3. let currNode = this._head;
  4. let currIndex = 0;
  5. while (currIndex < index) {
  6. currIndex += 1;
  7. currNode = currNode.next;
  8. }
  9. return currNode;
  10. }
  11. // 验证【衔接上面的链表实例】
  12. console.log(link.getNode(0));
  13. // Node { data: 1, next: Node { data: 2, next: Node { data: 3, next: null } } }
  14. console.log(link.getNode(3)); // null
2.4 insert方法

插入元素,需要考虑三种情况

插入尾部,相当于append

插入首部,替代_head并指向原有头部元素

中间,需要断开原有链接并重新组合(如下)

代码实现

</>复制代码

  1. // 在链表指定位置插入元素
  2. insert(index, data) {
  3. // 不满足条件的索引值
  4. if (index < 0 || index > this._length) return false;
  5. // 插入尾部
  6. if (index === this._length) return this.append(data);
  7. const insertNode = new Node(data);
  8. if (index === 0) {
  9. // 插入首部
  10. insertNode.next = this._head;
  11. this._head = insertNode;
  12. } else {
  13. // 找到原有位置节点
  14. const prevTargetNode = this.getNode(index - 1);
  15. const targetNode = prevTargetNode.next;
  16. // 重塑节点连接
  17. prevTargetNode.next = insertNode;
  18. insertNode.next = targetNode;
  19. }
  20. this._length += 1;
  21. return true;
  22. }
  23. // 验证
  24. link.insert(0, 0);
  25. link.insert(4, 4);
  26. link.insert(5, 5);
  27. link.print(); // 0 --> 1 --> 2 --> 3 --> 4 --> 5
2.5 removeAt方法

在指定位置删除元素同添加元素类似

首部:重新定义_head

其他:找到目标位置的前后元素,重塑连接,如果目标位置为尾部,则重新定义_tail

代码实现

</>复制代码

  1. // 在链表指定位置移除元素
  2. removeAt(index) {
  3. if (index < 0 || index >= this._length) return false;
  4. if (index === 0) {
  5. this._head = this._head.next;
  6. } else {
  7. const prevNode = this.getNode(index - 1);
  8. const delNode = prevNode.next;
  9. const nextNode = delNode.next;
  10. // 若移除为最后一个元素
  11. if (!nextNode) this._tail = prevNode;
  12. prevNode.next = nextNode;
  13. }
  14. this._length -= 1;
  15. return true;
  16. }
  17. // 验证
  18. link.removeAt(3);
  19. link.print(); // 0 --> 1 --> 2 --> 4 --> 5
2.6 其它方法

完整的链表代码,可点此获取

</>复制代码

  1. // 判断数据是否存在于链表内,存在返回index,否则返回-1
  2. indexOf(data) {
  3. let currNode = this._head;
  4. let index = 0;
  5. while (currNode) {
  6. if (currNode.data === data) return index;
  7. index += 1;
  8. currNode = currNode.next;
  9. }
  10. return -1;
  11. }
  12. getHead() {
  13. return this._head;
  14. }
  15. getTail() {
  16. return this._tail;
  17. }
  18. size() {
  19. return this._length;
  20. }
  21. isEmpty() {
  22. return !this._length;
  23. }
  24. clear() {
  25. this._head = null;
  26. this._tail = null;
  27. this._length = 0;
  28. }
三、链表的应用 3.1 基于链表实现的StackQueue

基于链表实现栈

</>复制代码

  1. class Stack {
  2. constructor() {
  3. this._link = new LinkedList();
  4. }
  5. push(item) {
  6. this._link.append(item);
  7. }
  8. pop() {
  9. const tailIndex = this._link - 1;
  10. return this._link.removeAt(tailIndex);
  11. }
  12. peek() {
  13. if (this._link.size() === 0) return undefined;
  14. return this._link.getTail().data;
  15. }
  16. size() {
  17. return this._link.size();
  18. }
  19. isEmpty() {
  20. return this._link.isEmpty();
  21. }
  22. clear() {
  23. this._link.clear()
  24. }
  25. }

基于链表实现队列

</>复制代码

  1. class Queue {
  2. constructor() {
  3. this._link = new LinkedList();
  4. }
  5. enqueue(item) {
  6. this._link.append(item);
  7. }
  8. dequeue() {
  9. return this._link.removeAt(0);
  10. }
  11. head() {
  12. if (this._link.size() === 0) return undefined;
  13. return this._link.getHead().data;
  14. }
  15. tail() {
  16. if (this._link.size() === 0) return undefined;
  17. return this._link.getTail().data;
  18. }
  19. size() {
  20. return this._link.size();
  21. }
  22. isEmpty() {
  23. return this._link.isEmpty();
  24. }
  25. clear() {
  26. this._link.clear()
  27. }
  28. }
3.2 链表翻转【面试常考】

(1)迭代法

迭代法的核心就是currNode.next = prevNode,然后从头部一次向后轮询

代码实现

</>复制代码

  1. reverse() {
  2. if (!this._head) return false;
  3. let prevNode = null;
  4. let currNode = this._head;
  5. while (currNode) {
  6. // 记录下一节点并重塑连接
  7. const nextNode = currNode.next;
  8. currNode.next = prevNode;
  9. // 轮询至下一节点
  10. prevNode = currNode;
  11. currNode = nextNode;
  12. }
  13. // 交换首尾
  14. let temp = this._tail;
  15. this._tail = this._head;
  16. this._head = temp;
  17. return true;
  18. }

(2)递归法

递归的本质就是执行到当前位置时,自己并不去解决,而是等下一阶段执行。直到递归终止条件,然后再依次向上执行

</>复制代码

  1. function _reverseByRecusive(node) {
  2. if (!node) return null;
  3. if (!node.next) return node; // 递归终止条件
  4. var reversedHead = _reverseByRecusive(node.next);
  5. node.next.next = node;
  6. node.next = null;
  7. return reversedHead;
  8. };
  9. _reverseByRecusive(this._head);
3.3 链表逆向输出

利用递归,反向输出

</>复制代码

  1. function _reversePrint(node){
  2. if(!node) return;// 递归终止条件
  3. _reversePrint(node.next);
  4. console.log(node.data);
  5. };
四、双向链表和循环链表 4.1 双向链表

双向链表和普通链表的区别在于,在链表中,一个节点只有链向下一个节点的链接,而在双向链表中,链接是双向的:一个链向下一个元素,另一个链向前一个元素,如下图

正是因为这种变化,使得链表相邻节点之间不仅只有单向关系,可以通过prev来访问当前节点的上一节点。相应的,双向循环链表的基类也有变化

</>复制代码

  1. class Node {
  2. constructor(data) {
  3. this.data = data;
  4. this.next = null;
  5. this.prev = null;
  6. }
  7. }

继承单向链表后,最终的双向循环链表DoublyLinkedList如下【prev对应的更改为NEW

</>复制代码

  1. class DoublyLinkedList extends LinkedList {
  2. constructor() {
  3. super();
  4. }
  5. append(data) {
  6. const newNode = new DoublyNode(data);
  7. if (this._length === 0) {
  8. this._head = newNode;
  9. this._tail = newNode;
  10. } else {
  11. newNode.prev = this._tail; // NEW
  12. this._tail.next = newNode;
  13. this._tail = newNode;
  14. }
  15. this._length += 1;
  16. return true;
  17. }
  18. insert(index, data) {
  19. if (index < 0 || index > this._length) return false;
  20. if (index === this._length) return this.append(data);
  21. const insertNode = new DoublyNode(data);
  22. if (index === 0) {
  23. insertNode.prev = null; // NEW
  24. this._head.prev = insertNode; // NEW
  25. insertNode.next = this._head;
  26. this._head = insertNode;
  27. } else {
  28. // 找到原有位置节点
  29. const prevTargetNode = this.getNode(index - 1);
  30. const targetNode = prevTargetNode.next;
  31. // 重塑节点连接
  32. prevTargetNode.next = insertNode;
  33. insertNode.next = targetNode;
  34. insertNode.prev = prevTargetNode; // NEW
  35. targetNode.prev = insertNode; // NEW
  36. }
  37. this._length += 1;
  38. return true;
  39. }
  40. removeAt(index) {
  41. if (index < 0 || index > this._length) return false;
  42. let delNode;
  43. if (index === 0) {
  44. delNode = this._head;
  45. this._head = this._head.next;
  46. this._head.prev = null; // NEW
  47. } else {
  48. const prevNode = this.getNode(index - 1);
  49. delNode = prevNode.next;
  50. const nextNode = delNode.next;
  51. // 若移除为最后一个元素
  52. if (!nextNode) {
  53. this._tail = prevNode;
  54. this._tail.next = null; // NEW
  55. } else {
  56. prevNode.next = nextNode; // NEW
  57. nextNode.prev = prevNode; // NEW
  58. }
  59. }
  60. this._length -= 1;
  61. return delNode.data;
  62. }
  63. }
4.2 循环链表

</>复制代码

  1. 循环链表可以像链表一样只有单向引用,也可以像双向链表一样有双向引用。循环链表和链 表之间唯一的区别在于,单向循环链表最后一个节点指向下一个节点的指针tail.next不是引用null, 而是指向第一个节点head,双向循环链表的第一个节点指向上一节点的指针head.prev不是引用null,而是指向最后一个节点tail

总结

链表的实现较于栈和队列的实现复杂许多,同样的,链表的功能更加强大

我们可以通过链表实现栈和队列,同样也可以通过链表来实现栈和队列的问题

链表更像是数组一样的基础数据结构,同时也避免了数组操作中删除或插入元素对其他元素的影响

上一篇:JS数据结构与算法_栈&队列
下一篇:JS数据结构与算法_集合&字典

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/101290.html

相关文章

  • 唠叨一下js对象哈希表那些事

    摘要:的扩展知识对于哈希表来说,最重要的莫过于生成哈希串的哈希算法和处理冲突的策略了。由于链表的查找需要遍历,如果我们将链表换成树或者哈希表结构,那么就能大幅提高冲突元素的查找效率。 最近在整理数据结构和算法相关的知识,小茄专门在github上开了个repo https://github.com/qieguo2016...,后续内容也会更新到这里,欢迎围观加星星! js对象 js中的对象是基...

    Nosee 评论0 收藏0
  • 探索vue源码之缓存篇

    摘要:中采用算法来实现缓存的高效管理。通过这两个属性,将缓存中的变量连接起来。以上图举例缓存这个对象中保存了三个变量。如果缓存数组为空,则返回将为传入参数的缓存对象标识为最常使用的,即,并调整双向链表,返回改变后的。 vue.js入坑也有了小半年的时间了,圈子里一直流传着其源码优雅、简洁的传说。最近的一次技术分享会,同事分享vue.js源码的缓存部分,鄙人将其整理出来,与大家一起学习 一、从...

    Forest10 评论0 收藏0
  • JS数据结构算法_栈&队列

    摘要:下一篇数据结构与算法链表写在前面说明数据结构与算法系列文章的代码和示例均可在此找到原计划是把你不知道的三部全部看完的,偶然间朋友推荐了数据结构与算法的一套入门视频,学之。手头上恰好有学习数据结构与算法的书籍,便转而先把数据结构与算法学习。 下一篇:JS数据结构与算法_链表 写在前面 说明:JS数据结构与算法 系列文章的代码和示例均可在此找到 原计划是把《你不知道的Javascript》...

    AndroidTraveler 评论0 收藏0
  • web技术分享| LRU 缓存淘汰算法

    摘要:双向链表用于管理缓存数据结点的顺序,新增数据和缓存命中最近被访问的数据被放置在结点,尾部的结点根据内存大小进行淘汰。 了解 LRU 之前,我们应该了解一下缓存,大家都知道计算机具有缓存内存,可以临时存储最常用的数据,当缓存数据超过一定大小时,系统会进行回收,以便释放出空间来缓存新的数据,但从系统中检索数据的成本...

    graf 评论0 收藏0

发表评论

0条评论

NeverSayNever

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<