javascript - 带递归的链表
问题描述
早上好,我正在学习,我想用递归函数制作一个链表,我一直在寻找示例,但我只找到了 Java 或其他类型的示例。从我所看到的情况来看,我想它会是这样的,但我无法让它工作。如果有人可以帮助我,我将不胜感激。谢谢你。
function ListRecurse () {
this.head = null;
this.size = 0;
}
function Node () {
this.data = data;
this.next = next;
}
ListRecurse.prototype.add = function (data) {
let NewNode = new Node(this.add(data), null)
if (this.head === null) {
this.head = NewNode;
}
else {
let current = this.head;
while (current.next) {
current = current.next;
}
current = NewNode
}
this.size ++;
}
解决方案
您可以利用存储最后一个节点并返回this
以获得流畅的界面。
function ListRecurse() {
this.head = null;
this.last = null;
this.size = 0;
}
function Node(data, next) {
this.data = data;
this.next = next;
}
ListRecurse.prototype.add = function(data) {
const node = new Node(data, null);
if (this.head === null) this.head = node;
else this.last.next = node;
this.last = node;
this.size++;
return this;
}
const list = new ListRecurse().add(1).add(2).add(3);
console.log(list);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- javascript - 功能组件未从 App 容器组件接收道具
- swift - Swift 中的 `!myValue.isEmpty` 和 `myValue.isEmpty == false` 有什么区别?
- batch-file - 在 Windows 中复制文件超级慢
- github - 通过脚本文件将 github 存储库安装为库
- php - 更新已读消息的状态
- vba - MS Access 列表框 - 从字段添加项目后,所有计算字段都转到“#Error”和“#Type!”
- asp.net-core - 如何让我的代码在 Linux (Ubuntu) 上检索环境变量?
- python-3.x - 是否可以在不解压缩 Python 的情况下删除 .zip 文件中的文件?
- wordpress - 将未列出的 You Tube 频道嵌入 WordPress 网页
- java - 如何从 DMN 模型中调用静态 Java 方法(Drools Business Central)