我正在获得所需的输出,即下面console.log
中第3次迭代的反向链表。
但我有return previous
,它仍然会返回第一次迭代的值。
即使console.log(previous)
代替return previous
,也会提供所需的输出。
但现在的问题是如何最终显示它?
有人可以解释一下,出了什么问题?
reverse(){
var current= this.head,previous=null;
while(current)
{
var next = current.next;
current.next = previous;
previous = current;
current = next;
console.log(previous); //I am getting my answer at the third iteration
}
return previous; //
}
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
}
add(value) {
var node = new Node(value);
if (this.head == null) {
this.head = node;
this.length++;
} else {
var current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
this.length++;
}
}
reverse() {
var current = this.head,
previous = null;
while (current) {
var next = current.next;
current.next = previous;
previous = current;
current = next;
console.log(previous);
}
return previous;
}
}
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
var ll = new LinkedList();
ll.add(3);
ll.add(2);
ll.add(7);
ll.reverse();
console.log(ll.head);

答案 0 :(得分:0)
它在return previous
所需要的只是为此特定问题调用函数ll.reverse()
或console.log(ll.reverse())
。
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
}
add(value) {
var node = new Node(value);
if (this.head == null) {
this.head = node;
this.length++;
} else {
var current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
this.length++;
}
}
reverse() {
var current = this.head,
previous = null;
while (current) {
var next = current.next;
current.next = previous;
previous = current;
current = next;
}
return previous;
}
}
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
var ll = new LinkedList();
ll.add(3);
ll.add(2);
ll.add(7);
ll.add(9);
console.log(ll.reverse());