Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么(双重)链表的pop功能不起作用?_Javascript_Doubly Linked List - Fatal编程技术网

Javascript 为什么(双重)链表的pop功能不起作用?

Javascript 为什么(双重)链表的pop功能不起作用?,javascript,doubly-linked-list,Javascript,Doubly Linked List,我正在解决编码挑战。当前是一个双链接列表 pop函数不起作用,它没有删除元素,我不明白为什么 我知道我可能应该使用对列表的最后一个和第一个元素的引用来实现解决方案。但这篇文章不是关于找到问题的解决方案,而是关于理解为什么当前的方法不起作用 export class LinkedList { constructor() { this.head = null } push(value) { if (this.head === null) { this.hea

我正在解决编码挑战。当前是一个双链接列表

pop函数不起作用,它没有删除元素,我不明白为什么

我知道我可能应该使用对列表的最后一个和第一个元素的引用来实现解决方案。但这篇文章不是关于找到问题的解决方案,而是关于理解为什么当前的方法不起作用

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

双链表的整个思想是能够从任意一端遍历它。然而,您只保留一个指向
头的指针。