双向链表-头的prev元素不可访问
我正在尝试在一个双向链表类中编写一个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
转载请注明出处:http://www.hjsszs.com/article/20230526/2067213.html