Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/475.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 双链接列表-head的上一个元素不可访问_Javascript_Doubly Linked List - Fatal编程技术网

Javascript 双链接列表-head的上一个元素不可访问

Javascript 双链接列表-head的上一个元素不可访问,javascript,doubly-linked-list,Javascript,Doubly Linked List,我正试图在一个双链表类中编写一个reverse函数。为了做到这一点,我想将“旧的”head节点保存在一个变量中,以便在我在head和tail之间切换之后访问它。因此,稍后当我尝试访问我保存的变量的prev节点时,代码抛出一个错误,表示变量值为null,无法访问prev。 请记住,之前我编写了一些简单的函数,如push、pop、shift等,没有任何错误 class Node { constructor(val) { this.val = val; this.next = nu

我正试图在一个双链表类中编写一个
reverse
函数。为了做到这一点,我想将“旧的”head节点保存在一个变量中,以便在我在head和tail之间切换之后访问它。因此,稍后当我尝试访问我保存的变量的
prev
节点时,代码抛出一个错误,表示变量值为null,无法访问
prev
。 请记住,之前我编写了一些简单的函数,如push、pop、shift等,没有任何错误

class Node {
  constructor(val) {
    this.val = val;
    this.next = null;
    this.prev = null;
  }
}

class DoublyLinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
    this.length = 0;
  }
  push(val) {
    var newNode = new Node(val);
    if (this.length === 0) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      this.tail.next = newNode;
      newNode.prev = this.tail;
      this.tail = newNode;
    }
    this.length++;
    return this;
  }

  reverse() {
    var current = this.head;
    this.head = this.tail;
    this.tail = current;
    var prev, next;
    for (let i = 0; 0 < this.length; i++) {
      prev = current.prev;
      next = current.next;
      current.next = prev;
      current.prev = next;
      current = next;
    }
    return this;
  }
}

let doubly = new DoublyLinkedList();
doubly.push("1");
doubly.push("2");
doubly.push("3");
doubly.push("4");
doubly.reverse();

您的代码中有一个小错误:

for (let i = 0; 0 < this.length; i++) {

如前所述,您的代码会在列表末尾进行迭代,设置current=null。

谢谢,我有一种感觉,它会是这样的,哈哈
for (let i = 0; 0 < this.length; i++) {
for (let i = 0; i < this.length; i++) {