【问题标题】:Doubly Linked List - prev element of head not accessible双向链表 - 头部的上一个元素不可访问
【发布时间】:2020-05-01 18:38:18
【问题描述】:

我正在尝试在双向链表类中编写 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】:

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

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

    应该如下(注意i而不是0在条件中):

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

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

    【讨论】:

    • 谢谢,有预感会是这样的哈哈
    猜你喜欢
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    相关资源
    最近更新 更多