翻译:疯狂的技术宅
说明:本文翻译自系列文章《Data Structures With JavaScript》,总共为四篇,原作者是在美国硅谷工作的工程师 Cho S. Kim 。这是本系列的第三篇。
英文:https://code.tutsplus.com/articles/data-structures-with-javascript-singly-linked-list-and-doubly-linked-list–cms-23392

计算机科学中最常见的两种数据结构是单链表和双链表。

在我学习这些数据结构的时候,曾经问我的同伴在生活中有没有类似的概念。我所听到的例子是购物清单和火车。但是我最终明白了,这些类比是不准确的,购物清单更类似队列,火车则更像是一个数组。

随着时间的推移,我终于发现了一个能够准确类比单链表和双向链表的例子:寻宝游戏。 如果你对寻宝游戏和链表之间的关系感到好奇,请继续往下读。

单链表

在计算机科学中,单链表是一种数据结构,保存了一系列链接的节点。 每个节点中包含数据和一个可指向另一个节点的指针。

单链列表的节点非常类似于寻宝游戏中的步骤。 每个步骤都包含一条消息(例如“您已到达法国”)和指向下一步骤的指针(例如“访问这些经纬度坐标”)。 当我们开始对这些单独的步骤进行排序并形成一系列步骤时,就是在玩一个寻宝游戏。

现在我们对单链表有了一个基本的概念,接下来讨论单链表的操作

单链表的操作

因为单链表包含节点,这两者的构造函数可以是两个独立的构造函数,所以我们需要些构造函数:NodeSinglyList

Node

  • data 存储数据
  • next 指向链表中下一个节点的指针

SinglyList

  • _length 用于表示链表中的节点数量
  • head 分配一个节点作为链表的头
  • add(value) 向链表中添加一个节点
  • searchNodeAt(position) 找到在列表中指定位置 n 上的节点
  • remove(position) 删除指定位置的节点

单链表的实现

在实现时,我们首先定义一个名为Node的构造函数,然后定义一个名为SinglyList的构造函数。

Node 的每个实例都应该能够存储数据并且能够指向另外一个节点。 要实现此功能,我们将分别创建两个属性:datanext

function Node(data) {this.data = data;this.next = null;
}

下一步我们定义SinglyList:

function SinglyList() {this._length = 0;this.head = null;
}

SinglyList 的每个实例有两个属性:_lengthhead。前者保存链表中的节点数,后者指向链表的头部,链表前面的节点。由于新创建的singlylist实例不包含任何节点,所以head的默认值是null_length的默认值是 0

单链表的方法

我们需要定义可以从链表中添加、查找和删除节点的方法。先从添加节点开始。

方法1/3: add(value)

太棒了,现在我们来实现将节点添加到链表的功能。

SinglyList.prototype.add = function(value) {var node = new Node(value),currentNode = this.head;// 1st use-case: an empty list if (!currentNode) {this.head = node;this._length++;return node;}// 2nd use-case: a non-empty listwhile (currentNode.next) {currentNode = currentNode.next;}currentNode.next = node;this._length++;return node;
};

把节点添加到链表会涉及很多步骤。先从方法开始。 我们使用add(value)的参数来创建一个节点的新实例,该节点被分配给名为node的变量。我们还声明了一个名为currentNode的变量,并将其初始化为链表的_head。 如果链表中还没有节点,那么head的值为null

实现了这一点之后,我们将处理两种情况。

第一种情况考虑将节点添加到空的链表中,如果head没有指向任何节点的话,那么将该node指定为链表的头,同时链表的长度加一,并返回node

第二种情况考虑将节点添加到飞空链表。我们进入while循环,在每次循环中,判断currentNode.next是否指向下一个节点。(第一次循环时,CurrentNode指向链表的头部。)

如果答案是否定的,我们会把currentnode.next指向新添加的节点,并返回node

如果答案是肯定的,就进入while循环。 在循环体中,我们将currentNode重新赋值给currentNode.next。 重复这个过程,直到currentNode.next不再指向任何。换句话说,currentNode指向链表中的最后一个节点。

while循环结束后,使currentnode.next指向新添加的节点,同时_length加1,最后返回node

方法2/3: searchNodeAt(position)

现在我们可以将节点添加到链表中了,但是还没有办法找到特定位置的节点。下面添加这个功能。创建一个名为searchNodeAt(position) 的方法,它接受一个名为 position 的参数。这个参数是个整数,用来表示链表中的位置n。

SinglyList.prototype.searchNodeAt = function(position) {var currentNode = this.head,length = this._length,count = 1,message = {failure: 'Failure: non-existent node in this list.'};// 1st use-case: an invalid position if (length === 0 || position < 1 || position > length) {throw new Error(message.failure);}// 2nd use-case: a valid position while (count < position) {currentNode = currentNode.next;count++;}return currentNode;
};

if中检查第一种情况:参数非法。

如果传给searchNodeAt(position)的索引是有效的,那么我们执行第二种情况 —— while循环。 在while的每次循环中,指向头的currentNode被重新指向链表中的下一个节点。

这个循环不断执行,一直到count等于position

方法3/3: remove(position)

最后一个方法是remove(position)

SinglyList.prototype.remove = function(position) {var currentNode = this.head,length = this._length,count = 0,message = {failure: 'Failure: non-existent node in this list.'},beforeNodeToDelete = null,nodeToDelete = null,deletedNode = null;// 1st use-case: an invalid positionif (position < 0 || position > length) {throw new Error(message.failure);}// 2nd use-case: the first node is removedif (position === 1) {this.head = currentNode.next;deletedNode = currentNode;currentNode = null;this._length--;return deletedNode;}// 3rd use-case: any other node is removedwhile (count < position) {beforeNodeToDelete = currentNode;nodeToDelete = currentNode.next;count++;}beforeNodeToDelete.next = nodeToDelete.next;deletedNode = nodeToDelete;nodeToDelete = null;this._length--;return deletedNode;
};

我们要实现的remove(position)涉及三种情况:

  1. 无效的位置作为参数传递。
  2. 第一个位置(链表的的`head)作为参数的传递。
  3. 一个合法的位置(不是第一个位置)作为参数的传递。

前两种情况是最简单的处理。 关于第一种情况,如果链表为空或传入的位置不存在,则会抛出错误。

第二种情况处理链表中第一个节点的删除,这也是头节点。 如果是这种情况,就执行下面的逻辑:

  1. 头被重新赋值给currentNode.next
  2. deletedNode指向currentNode
  3. currentNode被重新赋值为null。
  4. 将的链表的长度减1。
  5. 返回deletedNode

第三种情况是最难理解的。 其复杂性在于我们要在每一次循环中操作两个节点的必要性。 在每次循环中,需要处理要删除的节点和它前面的节点。当循环到要被删除的位置的节点时,循环终止。

在这一点上,我们涉及到三个节点:
beforeNodeToDelete, nodeToDelete, 和 deletedNode。删除nodeToDelete之前,必须先把它的next的值赋给beforeNodeToDeletenext,如果不清楚这一步骤的目的,可以提醒自己有一个节点负责链接其前后的其他节点,只需要删除这个节点,就可以把链表断开。

接下来,我们将deletedNode赋值给nodeToDelete。 然后我们将nodeToDelete的值设置为null,将列表的长度减1,最后返回deletedNode

单向链表的完整实现

以下是单向链表的完整实现:

function Node(data) {this.data = data;this.next = null;
}function SinglyList() {this._length = 0;this.head = null;
}SinglyList.prototype.add = function(value) {var node = new Node(value),currentNode = this.head;// 1st use-case: an empty listif (!currentNode) {this.head = node;this._length++;return node;}// 2nd use-case: a non-empty listwhile (currentNode.next) {currentNode = currentNode.next;}currentNode.next = node;this._length++;return node;
};SinglyList.prototype.searchNodeAt = function(position) {var currentNode = this.head,length = this._length,count = 1,message = {failure: 'Failure: non-existent node in this list.'};// 1st use-case: an invalid positionif (length === 0 || position < 1 || position > length) {throw new Error(message.failure);}// 2nd use-case: a valid positionwhile (count < position) {currentNode = currentNode.next;count++;}return currentNode;
};SinglyList.prototype.remove = function(position) {var currentNode = this.head,length = this._length,count = 0,message = {failure: 'Failure: non-existent node in this list.'},beforeNodeToDelete = null,nodeToDelete = null,deletedNode = null;// 1st use-case: an invalid positionif (position < 0 || position > length) {throw new Error(message.failure);}// 2nd use-case: the first node is removedif (position === 1) {this.head = currentNode.next;deletedNode = currentNode;currentNode = null;this._length--;return deletedNode;}// 3rd use-case: any other node is removedwhile (count < position) {beforeNodeToDelete = currentNode;nodeToDelete = currentNode.next;count++;}beforeNodeToDelete.next = nodeToDelete.next;deletedNode = nodeToDelete;nodeToDelete = null;this._length--;return deletedNode;
};

从单链表到双链表

我们已经完整的实现了单链表,这真是极好的。现在可以在一个占用费连续的空间的链表结构中,进行添加、删除和查找节点的操作了。

然而现在所有的操作都是从链表的起始位置开始,并运行到链表的结尾。换句话说,它们是单向的。

可能在某些情况下我们希望操作是双向的。如果你考虑了这种可能性,那么你刚才就是描述了一个双向链表。

双向链表

双向链表具有单链表的所有功能,并将其扩展为在链表中可以进行双向遍历。 换句话说,我们可从链表中第一个节点遍历到到最后一个节点;也可以从最后一个节点遍历到第一个节点。

在本节中,我们将重点关注双向链表和单链列表之间的差异。

双向链表的操作

我们的链表将包括两个构造函数:NodeDoublyList。看看他们是怎样运作的。

Node

  • data 存储数据。
  • next 指向链表中下一个节点的指针。
  • previous 指向链表中前一个节点的指针。

DoublyList

  • _length 保存链表中节点的个数
  • head 指定一个节点作为链表的头节点
  • tail 指定一个节点作为链表的尾节点
  • add(value) 向链表中添加一个节点
  • searchNodeAt(position) 找到在列表中指定位置 n 上的节点
  • remove(position) 删除链表中指定位置上的节点

双向链表的实现

现在开始写代码!

在实现中,将会创建一个名为Node的构造函数:

function Node(value) {this.data = value;this.previous = null;this.next = null;
}

想要实现双向链表的双向遍历,我们需要指向链表两个方向的属性。这些属性被命名为previousnext

接下来,我们需要实现DoublyList并添加三个属性:_lengthheadtail

与单链表不同,双向链表包含对链表开头和结尾节点的引用。 由于DoublyList刚被实例化时并不包含任何节点,所以headtail的默认值都被设置为null

function DoublyList() {this._length = 0;this.head = null;this.tail = null;
}

双向链表的方法

接下来我们讨论以下方法:add(value), remove(position), 和 searchNodeAt(position)。所有这些方法都用于单链表; 然而,它们必须备重写为可以双向遍历。

方法1/3 add(value)

DoublyList.prototype.add = function(value) {var node = new Node(value);if (this._length) {this.tail.next = node;node.previous = this.tail;this.tail = node;} else {this.head = node;this.tail = node;}this._length++;return node;
};

在这个方法中,存在两种可能。首先,如果链表是空的,则给它的headtail分配节点。其次,如果链表中已经存在节点,则查找链表的尾部并把心节点分配给tail.next;同样,我们需要配置新的尾部以供进行双向遍历。换句话说,我们需要把tail.previous设置为原来的尾部。

方法2/3 searchNodeAt(position)

searchNodeAt(position)的实现与单链表相同。 如果你忘记了如何实现它,请通过下面的代码回忆:

DoublyList.prototype.searchNodeAt = function(position) {var currentNode = this.head,length = this._length,count = 1,message = {failure: 'Failure: non-existent node in this list.'};// 1st use-case: an invalid position if (length === 0 || position < 1 || position > length) {throw new Error(message.failure);}// 2nd use-case: a valid position while (count < position) {currentNode = currentNode.next;count++;}return currentNode;
};

方法3/3 remove(position)

理解这个方法是最具挑战性的。我先写出代码,然后再解释它。

DoublyList.prototype.remove = function(position) {var currentNode = this.head,length = this._length,count = 1,message = {failure: 'Failure: non-existent node in this list.'},beforeNodeToDelete = null,nodeToDelete = null,deletedNode = null;// 1st use-case: an invalid positionif (length === 0 || position < 1 || position > length) {throw new Error(message.failure);}// 2nd use-case: the first node is removedif (position === 1) {this.head = currentNode.next;// 2nd use-case: there is a second nodeif (!this.head) {this.head.previous = null;// 2nd use-case: there is no second node} else {this.tail = null;}// 3rd use-case: the last node is removed} else if (position === this._length) {this.tail = this.tail.previous;this.tail.next = null;// 4th use-case: a middle node is removed} else {while (count < position) {currentNode = currentNode.next;count++;}beforeNodeToDelete = currentNode.previous;nodeToDelete = currentNode;afterNodeToDelete = currentNode.next;beforeNodeToDelete.next = afterNodeToDelete;afterNodeToDelete.previous = beforeNodeToDelete;deletedNode = nodeToDelete;nodeToDelete = null;}this._length--;return message.success;
};

remove(position) 处理以下四种情况:

  1. 如果remove(position)的参数传递的位置存在, 将会抛出一个错误。
  2. 如果remove(position)的参数传递的位置是链表的第一个节点(head),将把head赋值给deletedNode,然后把head重新分配到链表中的下一个节点。 此时,我们必须考虑链表中否存在多个节点。 如果答案为否,头部将被分配为null,之后进入if-else语句的if部分。 在if的代码中,还必须将tail设置为null —— 换句话说,我们返回到一个空的双向链表的初始状态。如果删除列表中的第一个节点,并且链表中存在多个节点,那么我们输入if-else语句的else部分。 在这种情况下,我们必须正确地将headprevious属性设置为null —— 在链表的头前面是没有节点的。
  3. 如果remove(position)的参数传递的位置是链表的尾部,首先把tail赋值给deletedNode,然后tail被重新赋值为尾部之前的那个节点,最后新尾部后面没有其他节点,需要将其next值设置为null
  4. 这里发生了很多事情,所以我将重点关注逻辑,而不是每一行代码。 一旦CurrentNode指向的节点是将要被remove(position)删除的节点时,就退出while循环。这时我们把nodeToDelete之后的节点重新赋值给beforeNodeToDelete.next。相应的,
    nodeToDelete之前的节点重新赋值给afterNodeToDelete.previous。——换句话说,我们把指向已删除节点的指针,改为指向正确的节点。最后,把nodeToDelete赋值为null

最后,把链表的长度减1,返回deletedNode

双向链表的完整实现

function Node(value) {this.data = value;this.previous = null;this.next = null;
}function DoublyList() {this._length = 0;this.head = null;this.tail = null;
}DoublyList.prototype.add = function(value) {var node = new Node(value);if (this._length) {this.tail.next = node;node.previous = this.tail;this.tail = node;} else {this.head = node;this.tail = node;}this._length++;return node;
};DoublyList.prototype.searchNodeAt = function(position) {var currentNode = this.head,length = this._length,count = 1,message = {failure: 'Failure: non-existent node in this list.'};// 1st use-case: an invalid positionif (length === 0 || position < 1 || position > length) {throw new Error(message.failure);}// 2nd use-case: a valid positionwhile (count < position) {currentNode = currentNode.next;count++;}return currentNode;
};DoublyList.prototype.remove = function(position) {var currentNode = this.head,length = this._length,count = 1,message = {failure: 'Failure: non-existent node in this list.'},beforeNodeToDelete = null,nodeToDelete = null,deletedNode = null;// 1st use-case: an invalid positionif (length === 0 || position < 1 || position > length) {throw new Error(message.failure);}// 2nd use-case: the first node is removedif (position === 1) {this.head = currentNode.next;// 2nd use-case: there is a second nodeif (!this.head) {this.head.previous = null;// 2nd use-case: there is no second node} else {this.tail = null;}// 3rd use-case: the last node is removed} else if (position === this._length) {this.tail = this.tail.previous;this.tail.next = null;// 4th use-case: a middle node is removed} else {while (count < position) {currentNode = currentNode.next;count++;}beforeNodeToDelete = currentNode.previous;nodeToDelete = currentNode;afterNodeToDelete = currentNode.next;beforeNodeToDelete.next = afterNodeToDelete;afterNodeToDelete.previous = beforeNodeToDelete;deletedNode = nodeToDelete;nodeToDelete = null;}this._length--;return message.success;
};

总结

本文中已经介绍了很多信息。 如果其中任何地方看起来令人困惑,就再读一遍并查看代码。如果它最终对你有所帮助,我会感到自豪。你刚刚揭开了一个单链表和双向链表的秘密,可以把这些数据结构添加到自己的编码工具弹药库中!

欢迎扫描二维码关注公众号,每天推送我翻译的技术文章。

JavaScript数据结构(3):单向链表与双向链表相关推荐

  1. 数据结构与算法之反转单向链表和双向链表

    数据结构与算法之反转单向链表和双向链表 目录 反转单向链表和双向链表 1. 反转单向链表和双向链表 题目描述 代码实现 public class Code_ReverseList {public st ...

  2. 数据结构 (二) ----- 单向链表双向链表

    相关文章: <数据结构 (一) ----- 数据结构基本概念&基于数组实现线性表> <数据结构 (二) ----- 单向链表&双向链表> 文章目录 单链表 一. ...

  3. 数据结构——数组、单向链表、双向链表

    原文:http://www.cnblogs.com/skywang12345/p/3561803.html 线性表是一种线性结构,它是具有相同类型的n(n≥0)个数据元素组成的有限序列.本章先介绍线性 ...

  4. JavaScript数据结构与算法——链表详解(下)

    在JavaScript数据结构与算法--链表详解(上)中,我们探讨了一下链表的定义.实现原理以及单链表的实现.接下来我们进一步了解一下链表的其他内容. 1.双向链表 双向链表实现原理图: 与单向链表不 ...

  5. 长风破浪会有时:单向链表、双向链表和循环链表图文解析

    链表的种类有很多.我们常常会用到的链表有:单向链表.双向链表和循环链表. 链表不同于数组的地方在于:它的物理存储结构是非连续的,也就是说链表在内存中不是连续的,并且无序.它是通过数据节点的互相指向实现 ...

  6. JavaScript数据结构与算法——链表详解(上)

    注:与之前JavaScript数据结构与算法系列博客不同的是,从这篇开始,此系列博客采用es6语法编写,这样在学数据结构的同时还能对ECMAScript6有进一步的认识,如需先了解es6语法请浏览ht ...

  7. Java版数据结构之单向链表 新增,有序新增的两种方式,修改和删除(CRUD)

    Java版数据结构之单向链表 CRUD Java版数据结构之单向链表 新增,有序新增的两种方式,修改和删除; 留了一个疑问; 我的代码仓库:https://github.com/zhuangbinan ...

  8. Java版数据结构之单向链表

    Java版数据结构之单向链表 我的代码仓库:https://github.com/zhuangbinan/datastructure package club.zhuangbinan.linkedli ...

  9. 《恋上数据结构第1季》单向链表、双向链表

    链表(Linked List) 链表的接口设计 单向链表(SingleLinkedList) 获取元素 – get() 清空元素 – clear() 添加元素 – add(int index, E e ...

最新文章

  1. movie bookmark
  2. MFC中Mat实现打开本地图片
  3. mybatis mysql usegeneratedkeys_mybatis中useGeneratedKeys用法--插入数据库后获取主键值
  4. Hello Indigo
  5. 电商促销类插画素材,适合各种活动banner设计
  6. NUC1931 Problem D 区间素数【素数筛选】
  7. iOS中的Runloop
  8. 防毒墙APT防护抗DDOS攻击
  9. MAC苹果应用软件,财务管理,三D制图,清理神器
  10. Maven Setting.xml配置文件下载 阿里云镜像 下载可用
  11. Hadoop系列五之版本差别
  12. 对外汉语偏误语料库_对外汉语偏误汇总
  13. clickonce程序部署后,启动不成功的问题
  14. security 二层交换安全
  15. inline内联函数 static静态函数 普通函数区别
  16. 混杂模式和非混杂模式
  17. Octotree | 树形展示 GitHub 项目代码结构
  18. iOS VS Android ,10年之战,谁是最后赢家?
  19. JAVA代码审计之WebGoat靶场SQL注入
  20. Android 极光推送SDK集成

热门文章

  1. 医疗时鲜资讯:在线咨询!=远程医疗?
  2. php实现联系客服(在线咨询)
  3. 自己动手组装的第一台电脑
  4. 利用Python制作简易的点赞器
  5. 攻防世界-坚持60s
  6. 招聘广告缩略语中英文对照
  7. SAR Speckle reduction--Charles Deledalle - Software--Open Source
  8. 死锁、活锁、饥饿定位死锁解决死锁
  9. 《J2SE 回炉再造08》-------溺水狗
  10. js发送post请求