【发布时间】:2020-07-24 12:25:51
【问题描述】:
根据我在下面的实现,我无法反转链接列表。我在这里做错了什么或遗漏了什么?
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]。
【问题讨论】:
标签: javascript linked-list singly-linked-list