双重链接列表 - 头部的前一个元素不可访问。

问题描述 投票:1回答:1

我想写一个 reverse 函数在一个双关联列表类中。为了做到这一点,我想把 "旧的 "头部节点保存在一个变量中,以便以后在头部和尾部之间切换后访问它。所以以后当我试图访问 prev 节点,我保存的代码抛出一个错误,说变量值是空的,并且 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();

我的 reverse 函数还没有测试,因为我被我提到的问题卡住了.错误(在循环的第一行抛出)。

TypeError: Cannot read property 'prev' of null
javascript doubly-linked-list
1个回答
2
投票

在你的代码中,有一个小小的错别字。

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

应该是这样的(注意 i 而不是 0 中的条件)。)

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

就像你写的那样,你的代码从列表末尾开始迭代,设置current=null。

© www.soinside.com 2019 - 2024. All rights reserved.