如何在JavaScript中实现链接列表
If you are learning data structures, a linked list is one data structure you should know. If you do not really understand it or how it is implemented in JavaScript, this article is here to help you.
如果您正在学习数据结构,则链表是您应该知道的一种数据结构。 如果您不太了解它或如何在JavaScript中实现它,本文将为您提供帮助。
In this article, we will discuss what a linked list is, how it is different from an array, and how to implement it in JavaScript. Let's get started.
在本文中,我们将讨论什么是链表,链表与数组的不同之处以及如何在JavaScript中实现。 让我们开始吧。
什么是链表? (What is a Linked List?)
A linked list is a linear data structure similar to an array. However, unlike arrays, elements are not stored in a particular memory location or index. Rather each element is a separate object that contains a pointer or a link to the next object in that list.
链表是类似于数组的线性数据结构。 但是,与数组不同,元素不存储在特定的存储位置或索引中。 而是每个元素都是一个单独的对象,其中包含一个指针或指向该列表中下一个对象的链接。
Each element (commonly called nodes) contains two items: the data stored and a link to the next node. The data can be any valid data type. You can see this illustrated in the diagram below.
每个元素(通常称为节点)包含两项:存储的数据和到下一个节点的链接。 数据可以是任何有效的数据类型。 您可以在下图中看到这一点。
The entry point to a linked list is called the head. The head is a reference to the first node in the linked list. The last node on the list points to null. If a list is empty, the head is a null reference.
链接列表的入口称为头。 头是对链表中第一个节点的引用。 列表上的最后一个节点指向null。 如果列表为空,则标头为空引用。
In JavaScript, a linked list looks like this:
在JavaScript中,链接列表如下所示:
const list = {head: {value: 6next: {value: 10 next: {value: 12next: {value: 3next: null }}}}}
};
链表的优点 (An advantage of Linked Lists)
- Nodes can easily be removed or added from a linked list without reorganizing the entire data structure. This is one advantage it has over arrays.可以轻松地从链接列表中删除或添加节点,而无需重新组织整个数据结构。 这是它比数组具有的优势之一。
链表的缺点 (Disadvantages of Linked Lists)
- Search operations are slow in linked lists. Unlike arrays, random access of data elements is not allowed. Nodes are accessed sequentially starting from the first node.链接列表中的搜索操作很慢。 与数组不同,不允许随机访问数据元素。 从第一个节点开始依次访问节点。
- It uses more memory than arrays because of the storage of the pointers.由于指针的存储,它比数组使用更多的内存。
链接列表的类型 (Types of Linked Lists)
There are three types of linked lists:
链接列表有三种类型:
Singly Linked Lists: Each node contains only one pointer to the next node. This is what we have been talking about so far.
单链接列表 :每个节点仅包含一个指向下一个节点的指针。 到目前为止,这就是我们一直在谈论的内容。
Doubly Linked Lists: Each node contains two pointers, a pointer to the next node and a pointer to the previous node.
双链表 :每个节点包含两个指针,一个指向下一个节点的指针和一个指向上一个节点的指针。
Circular Linked Lists: Circular linked lists are a variation of a linked list in which the last node points to the first node or any other node before it, thereby forming a loop.
循环链表 :循环链表是链表的一种变体,其中最后一个节点指向第一个节点或它之前的任何其他节点,从而形成一个循环。
在JavaScript中实现列表节点 (Implementing a List Node in JavaScript)
As stated earlier, a list node contains two items: the data and the pointer to the next node. We can implement a list node in JavaScript as follows:
如前所述,列表节点包含两项:数据和指向下一个节点的指针。 我们可以在JavaScript中实现列表节点,如下所示:
class ListNode {constructor(data) {this.data = datathis.next = null }
}
在JavaScript中实现链接列表 (Implementing a Linked List in JavaScript)
The code below shows the implementation of a linked list class with a constructor. Notice that if the head node is not passed, the head is initialised to null.
下面的代码显示了使用构造函数的链表类的实现。 请注意,如果未传递头节点,则头将初始化为null。
class LinkedList {constructor(head = null) {this.head = head}
}
全部放在一起 (Putting it all together)
Let's create a linked list with the class we just created. First, we create two list nodes, node1
and node2
and a pointer from node 1 to node 2.
让我们用刚刚创建的类创建一个链表。 首先,我们创建了两个列表中的节点, node1
和node2
和节点1到节点2的指针。
let node1 = new ListNode(2)
let node2 = new ListNode(5)
node1.next = node2
Next, we'll create a Linked list with the node1
.
接下来,我们将使用node1
创建一个链接列表。
let list = new LinkedList(node1)
Let's try to access the nodes in the list we just created.
让我们尝试访问刚刚创建的列表中的节点。
console.log(list.head.next.data) //returns 5
一些LinkedList方法 (Some LinkedList methods)
Next up, we will implement four helper methods for the linked list. They are:
接下来,我们将为链接列表实现四种帮助方法。 他们是:
- size()尺寸()
- clear()明确()
- getLast()getLast()
- getFirst()getFirst()
1. size() (1. size())
This method returns the number of nodes present in the linked list.
此方法返回链表中存在的节点数。
size() {let count = 0; let node = this.head;while (node) {count++;node = node.next}return count;
}
2. clear() (2. clear())
This method empties out the list.
此方法清空列表。
clear() {this.head = null;
}
3. getLast() (3. getLast())
This method returns the last node of the linked list.
此方法返回链表的最后一个节点。
getLast() {let lastNode = this.head;if (lastNode) {while (lastNode.next) {lastNode = lastNode.next}}return lastNode
}
4. getFirst() (4. getFirst())
This method returns the first node of the linked list.
此方法返回链表的第一个节点。
getFirst() {return this.head;
}
摘要 (Summary)
In this article, we discussed what a linked list is and how it can be implemented in JavaScript. We also discussed the different types of linked lists as well as their overall advantages and disadvantages.
在本文中,我们讨论了什么是链表以及如何在JavaScript中实现链表。 我们还讨论了链表的不同类型及其整体优缺点。
I hope you enjoyed reading it.
希望您喜欢阅读。
Want to get notified when I publish a new article? Click here.
想要在我发表新文章时得到通知吗? 请点击这里 。
翻译自: https://www.freecodecamp.org/news/implementing-a-linked-list-in-javascript/
相关文章:

SVG.path_不连续的线段
1、之前 用<path/>画的 线段等 都是连续的,想知道 是否能画 不连续的线段等 结论:可以 2、测试代码: <?xml version"1.0" encoding"UTF-8"?> <svg width"1000" height"800" viewBo…

Leetcode 之Binary Tree Postorder Traversal(44)
后序遍历,比先序和中序都要复杂。访问一个结点前,需要先判断其右孩子是否被访问过。如果是,则可以访问该结点;否则,需要先处理右子树。 vector<int> postorderTraversal(TreeNode *root){vector<int> resu…

如何创建自己的ESLint配置包
ESLint is a powerful tool that helps you enforce consistent coding conventions and ensure quality in your JavaScript codebase. ESLint是一个功能强大的工具,可帮助您实施一致的编码约定并确保JavaScript代码库的质量。 Coding conventions are sometimes …

MySQL更新命令_UPDATE
创建测试表 mysql> CREATE TABLE product (-> proID int(11) NOT NULL AUTO_INCREMENT COMMENT 商品表主键,-> price decimal(10,2) NOT NULL COMMENT 商品价格,-> type int(11) NOT NULL COMMENT 商品类别(0生鲜,1食品,2生活),-> dtime datetime N…

KVC与KVO
1、键值编码KVC常用的KVC操作方法如下:• 动态设置: setValue:属性值 forKey:属性名(用于简单路径)、setValue:属性值 forKeyPath:属性路径(用于复合路径,例如Person有一个Account类型的属性,…

javaScript 工作必知(三) String .的方法从何而来?
String 我们知道javascript 包括:number,string,boolean,null,undefined 基本类型和Object 类型。 在我的认知中,方法属性应该是对象才可以具有的。 var str"hello,world";var sstr.subString(1,4);//ellalert(typeof…

s3 aws_您需要了解的有关AWS S3的所有信息
s3 awsThis article will provide an in-depth introduction to AWS S3 — the secure, scalable, and super cheap storage service from Amazon Web Services.本文将深入介绍AWS S3-来自Amazon Web Services的安全,可扩展和超便宜的存储服务。 If you have eve…

untitled与前端——初学
“前端” 啥? 百度百科: 就是制作一网页界面。比如360浏览器打开, 包括界面布局设计,搜索框,点击字或图标跳到另一个页面等。 软件Untitled 下载网址:http://www.jetbrains.com/ 下拉 点download࿰…

NSThread
NSThread是轻量级的多线程开发,使用起来也并不复杂,但是使用NSThread需要自己管理线程生命周期。 可以使用对象方法: (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)argument 直接将操作添加到线程中并…

异步发送邮件、短信、微信
用户创建订单的按钮点击后,服务器存储这个订单信息后,调用发送短信、邮件、微信的接口,发送消息。而发送短信、邮件、微信都要涉及第三方的处理,服务器又要发送一个新的包裹给一个新的服务器,告诉他帮我发一个信息出去…

英语面试简短问题_用简单的英语解释产品设计
英语面试简短问题Product design is the process you go through when you conceptualize and build a product.产品设计是概念化和构建产品时要经历的过程。 The path to building – hardware, software, or even simple prototypes – has different steps and approaches.…

6-12 二叉搜索树的操作集
6-12 二叉搜索树的操作集(30 分) 本题要求实现给定二叉搜索树的5种常用操作。 函数接口定义: BinTree Insert( BinTree BST, ElementType X ); BinTree Delete( BinTree BST, ElementType X ); Position Find( BinTree BST, ElementType X );…

iOS关于自定义rightBarButtonItem
在常见iOS开发中,我们常遇到这样的需求,如下: 我们需要自定义导航栏右侧按钮,常见的自定义包装按钮如下: //设置rightItem; UIButton *btn [UIButton buttonWithType:UIButtonTypeCustom]; btn.frame CGRectMake(0, 0, 40, 30); btn.selected NO; [btn setTitle:"管理&…

URL里汉字转码
URL里面不能包含中文。 解决办法:进行转码 NSString *urlStr[NSString stringWithFormat:kLotteryBar_putOutReviewUrl,_token,self.reviews_id,_User_Id,reviews_content]; urlStr[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

electron.js_在使用Electron.js之前我希望知道的事情
electron.jsIn this article, Ill share how you can avoid some of the mistakes I made when learning about Electron.js 🤦♂️. I hope it helps!在本文中,我将分享如何避免在学习Electron.js 🤦🤦️时犯的一些错误。 希…

Entity Framework的启动速度优化
最近开发的服务放到IIS上寄宿之后,遇到一些现象,比如刚部署之后,第一次启动很慢;程序放置一会儿,再次请求也会比较慢。比如第一个问题,可以解释为初次请求某一个服务的时候,需要把程序集加载到内…

NSURLConnection的简单使用
遵循代理:NSURLConnectionDataDelegate -(void)fetchWebData:(id)sender{ self.isLoadingYES;NSString *urlStrkRequestUrlStr(self.page);NSURL *url[NSURL URLWithString:urlStr];NSURLRequest *request[NSURLRequest requestWithURL:url];self.connection[N…

tcp reno_如何使用称为Reno Expo的简单入门工具包构建全栈应用程序
tcp renoBuilding any new project from scratch can be intimidating. Theres a lot to decide before you can even start coding to test out your idea.从头开始构建任何新项目都可能令人生畏。 在开始编码以检验您的想法之前,还有很多决定。 How are you buil…

不同命名空间的对象二进制反序列化问题
本质上说,这并不是二进制序列化的问题,甚至不关序列化的问题。 你想要的是在两个内部结构一致但在不同命名空间(甚至不同项目)的同名类间做类型转换。 这个问题很常见,因为实际工作中经常会有此类需求,但是…

对大文件的断点续传
注:#import "YGFileDownloader.h"是对NSURLConnection的简单封装 #import "YGResumeDownloadViewController.h" #import "NSStringutil.h"#import "YGFileDownloader.h"#define URL "http://dlsw.baidu.com/sw-searc…

bootstrap modal 弹出效果
window.showMsg function (msg) {//显示悬浮窗$("#autoCloseModal").modal("show")//设置文本内容$("#autoCloseModal #autoCloseModalBody").html("")$("#autoCloseModal #autoCloseModalBody").html(msg);//两秒后消失se…

68-95-99规则–以普通英语解释正态分布
Meet Mason. Hes an average American 40-year-old: 5 foot 10 inches tall and earning $47,000 per year before tax.认识梅森。 他平均年龄40岁,身高5英尺10英寸,每年税前收入$ 47,000。 How often would you expect to meet someone who earns 10x …

Uva 10048 - Audiophobia (Floyd变形)
题目链接 https://vjudge.net/problem/UVA-10048 【题意】 输入一个C个点,S个边(C<100,S<1000)的无向图,边权表示该路径上的噪声值,当你从某点出发到另外一点时希望路上经过的最大噪声值最小,输入一…

ubuntu联网经常掉线的解决方法
打开电脑,发现联网的图标没有连接上,想手动点击连接上,却发现选项是灰色(不可选) 或者是图标显示已经连接上了,但浏览器就是无法上网,也ping不通 此时打开终端输入 sudo /etc/init.d/network-ma…

JSON和XML
JSONJSON(JavaScript Object Notation)一种轻量级的数据交换格式,具有良好的可读和便于快速编写的特性。可在不同平台之间进行数据交换。JSON采用兼容性很高的、完全独立于语言文本格式,同时也具备类似于C语言的习惯(包括C, C, C#, Java, JavaScript, Pe…

deno使用rust_如何在Deno和Oak中使用MySQL
deno使用rustI recently wrote about how to make a Todo API in Deno Oak (without using a database). You can find the repo under chapter_1:oak on GitHub. 我最近写了关于如何在Deno Oak(不使用数据库)中制作Todo API的文章 。 您可以在GitHub上的Chapter_1࿱…

Zookeeper 安装和配置
Zookeeper 安装和配置01 ZooKeeper的安装与部署02转载于:https://www.cnblogs.com/hfultrastrong/p/8414587.html

iOS中的各种手势
/**基类UIGestureRecognizerUITapGestureRecognizer Tap 点击UIPanGestureRecognizer Pan (慢速滑动,拖移)UILongPressGestureRecognizer LongPress (长按)UIPinchGestureRecognizer Pinch (捏合,两手指往内或外拨动&…

Nginx问题定位之监控进程异常退出
nginx在运行过程中是否稳定,是否有异常退出过?这里总结几项平时会用到的小技巧。 1. 在error.log中查看是否有signal项,如果有,看看signal是多少。 比如,这是一个异常退出的情况: $grep signal error.log20…

k3应付系统初始化应付票据_在家工作时应付无尽干扰的真实感觉
k3应付系统初始化应付票据Whether or not you have worked remotely before, you’ve likely never had to share your “home office” with your partner and two children. 无论您以前是否在远程工作,您都可能从未与伴侣和两个孩子共享“家庭办公室”。 Before …