基于下面的实现,我在反转链表时遇到了问题。我在这里是不是做错了什么?
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class SinglyLinkedList {
constructor() {
this.head = null;
this.length = 0;
}
push(val) {
var newNode = new Node(val);
var current = this.head;
if (!this.head)
this.head = newNode;
else {
// iterate to the end of the
// list
while (current.next) {
current = current.next;
}
// add node
current.next = newNode;
}
this.length++;
return this;
}
// reverse the list
reverse() {
var prev = null;
var curr = this.head;
while (curr !== null) {
var temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
return this;
}
print() {
var arr = []
var current = this.head;
while(current) {
arr.push(current.val);
current = current.next;
}
console.log(arr);
}
}
以下是我创建对象并推送一些节点时的实现
var list = new SinglyLinkedList();
list.push(1);
list.push(2);
list.push(3);
list.push(4);
每次我运行list.reverse()
然后运行list.print()
时,它只打印[1]
而不打印[4,3,2,1]
。
您正确地反转了节点之间的链接,但从未更改this.head
指向的内容,因此它现在指向列表的末尾,而不是列表的前面。因此,当您调用print时,print将从最后一个节点开始,然后无处可去。
reverse() {
var prev = null;
var curr = this.head;
while (curr !== null) {
var temp = curr.next;
curr.next = prev;
prev = curr;
curr = temp;
}
this.head = prev; // <--- added
return this;
}
您尚未更新reverse
方法中的head
属性。只需在while
循环之后添加this.head = prev;
,我相信它应该可以工作。