0
我想使用工厂函数的方式来实现一个对象,并试图与链接列表示例,其中我初始化一个空的链接列表,然后尝试添加节点,在添加方法方法I如果未设置,则设置头部,否则将该节点添加到链中的最后一个节点。 问题是,头从来没有出现设置,任何想法为什么?工厂函数链表问题
"use strict"
const niceLog = s => {
console.log(JSON.stringify(s, null, 2))
}
function linkedList() {
let head
const node = data => {
return {
data,
next: null
}
}
const add = data => {
if (!head) {
head = node(data)
} else {
const end = node(data)
let n = head
while (n.next) n = n.next
n.next = end
}
}
const del = data => {
let n = head
if (n.data === data) head = head.next
while (n.next) {
if (n.next.data === data) {
n.next = n.next.next
return
}
n = n.next
}
}
return {
head,
add,
del
}
}
const ll = linkedList()
ll.add('cheese')
ll.add('crackers')
ll.add('tea')
ll.add('coffee')
niceLog(ll) // {}
这里是ES6类语法等效代码不工作,(我曾听说工厂功能更好,因为它们避免新的问题和这个关键词没有被正确设定这就是为什么我试图使用工厂功能)
const niceLog = s => {
console.log(JSON.stringify(s, null, 2))
}
class Node {
constructor(data) {
this.data = data
this.next = null
}
}
class LinkedList {
constructor() {
this.head = null
}
add(data){
if (!this.head) {
this.head = new Node(data)
} else {
const end = new Node(data)
let n = this.head
while (n.next) n = n.next
n.next = end
}
}
del(data) {
let n = this.head
if (n.data === data) this.head = this.head.next
while (n.next) {
if (n.next.data === data) {
n.next = n.next.next
return
}
n = n.next
}
}
}
const ll = new LinkedList()
ll.add('cheese')
ll.add('crackers')
ll.add('tea')
ll.add('coffee')
niceLog(ll) // output =
"head": {
"data": "cheese",
"next": {
"data": "crackers",
"next": {
"data": "tea",
"next": {
"data": "coffee",
"next": null
}
}
}
}
}
所以...你的问题是什么? –
我现在添加了问题部分! – Heisenberg