【发布时间】: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