为什么(双向)链表的弹出功能不起作用?
Why is this pop function of a (doubly) linked list not working?
我正在解决编码挑战。目前是双向链表。
弹出函数不起作用,它没有删除元素,我不明白为什么。
我知道我应该使用对列表的最后一个和第一个元素的引用来实现解决方案。但这 post 不是要找到问题的解决方案,而是要了解为什么当前的方法不起作用。
export class LinkedList {
constructor() {
this.head = null
}
push(value) {
if (this.head === null) {
this.head = new Node(value, null)
return
}
var cur = this.head
while (cur.next !== null) {
cur = cur.next
}
cur.next = new Node(value, cur)
return
}
pop() {
if (this.head === null) { return null }
var cur = this.head
while (cur.next !== null) {
cur = cur.next
}
// here I am doing sth wrong, I guess.
// the thinking is that when I set the (one) reference to the last element (cur) to null,
// it should be removed from the list; why would it not be?
let value = cur.value
cur = null
return value
}
}
class Node {
constructor(value, prev) {
this.value = value;
this.next = null;
this.prev = prev;
}
}
由于帮助我找出方法问题的评论已被删除,我想在这里自己解释一下。
我误以为说 cur = null
我可以更改内存位置中的值,这将影响对该位置的所有引用。相反,我只是将变量 cur 从持有引用更改为持有值 null
.
我应该做的是cur.prev.next = null
。
我正在解决编码挑战。目前是双向链表。
弹出函数不起作用,它没有删除元素,我不明白为什么。
我知道我应该使用对列表的最后一个和第一个元素的引用来实现解决方案。但这 post 不是要找到问题的解决方案,而是要了解为什么当前的方法不起作用。
export class LinkedList {
constructor() {
this.head = null
}
push(value) {
if (this.head === null) {
this.head = new Node(value, null)
return
}
var cur = this.head
while (cur.next !== null) {
cur = cur.next
}
cur.next = new Node(value, cur)
return
}
pop() {
if (this.head === null) { return null }
var cur = this.head
while (cur.next !== null) {
cur = cur.next
}
// here I am doing sth wrong, I guess.
// the thinking is that when I set the (one) reference to the last element (cur) to null,
// it should be removed from the list; why would it not be?
let value = cur.value
cur = null
return value
}
}
class Node {
constructor(value, prev) {
this.value = value;
this.next = null;
this.prev = prev;
}
}
由于帮助我找出方法问题的评论已被删除,我想在这里自己解释一下。
我误以为说 cur = null
我可以更改内存位置中的值,这将影响对该位置的所有引用。相反,我只是将变量 cur 从持有引用更改为持有值 null
.
我应该做的是cur.prev.next = null
。