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++) {