【发布时间】:2022-01-08 15:56:47
【问题描述】:
好的,我正在学习数据结构,我的教程遵循class 语法。所以现在我正试图将其转换为 function 声明,因为我想使用该符号练习链接列表。有人可以帮我转换吗?我只需要转换一种方法,其余的我就可以完成。
这是我使用class 语法的代码:
class Node {
constructor( val ) {
this.val = val;
this.next = null;
}
}
class SinglyLinkedList {
constructor () {
this.head = null;
this.tail = null;
this.length = 0;
}
push( val ) {
const newNode = new Node( val );
if ( !this.head ) {
this.head = newNode;
this.tail = this.head;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.length++
return this;
}
}
const list = new SinglyLinkedList();
list.push( 'HELLO' );
list.push( 'WORLD' );
这是我迄今为止尝试实现基于函数的方法:
function Node( val ) {
this.val = val;
this.next = null;
}
let head = null;
let tail = null;
let length = 0;
const SinglyLinkedListFunc = function() {
const newNode = new Node( 'HELLO' );
};
SinglyLinkedListFunc()
这是我目前所能达到的。我被它困住了,我不知道下一步该做什么。有人请帮忙
【问题讨论】:
-
呃,链表(节点)是一个对象。您不能将其更改为局部变量。
-
仅仅因为你使用了构造函数并不能使它起作用。任何。您需要两个构造函数。一个用于节点,一个用于列表。
-
真正实用(因此:不可变)的方法会使
push效率低下,因为它需要复制整个列表。你为什么想要那个? -
@s.khan “功能”并不意味着您不再使用对象或类。相反,你仍然应该让你的代码更有条理!但是,函数式方法意味着您不应再修改(变异)您的对象,而是创建作为操作(方法、函数)结果返回的新对象。
-
@ScottSauyet,当然,prepending 可以通过函数式方法有效地完成,但不是 appending,这是 Asker 用他们的
push。无论如何,Asker 最终要求的不是函数式方法,而是不使用class语法的版本。
标签: javascript algorithm data-structures linked-list singly-linked-list