【发布时间】:2018-08-24 02:03:23
【问题描述】:
我的代码在查找链接列表的特定索引处的元素时遇到问题。
findElement(index) {
let currentNode = this.head;
let count = 0;
while (currentNode != null) {
if (count === index) {
return currentNode;
count++;
currentNode = currentNode.next;
}
return -1;
}
}
当我这样做时,我得到的是整个链表而不是一个特定的节点。因此,如果我使用 console.log(list.findElement(0)),我会得到整个链表。但是如果我控制台日志console.log(list.findElement(1)),我得到-1。但我想要的是第二个节点。下面是我的其余代码。不完全确定我的 findElement 函数出了什么问题。
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
//Length
this.length = 0;
}
//Push-front
pushFront(value) {
let node = new Node(value);
node.next = this.head;
this.head = node;
this.length++;
}
//Pop-front
popFront() {
if (this.head != null) {
this.head = this.head.next;
}
this.length--;
}
//Push-back
pushBack(value) {
let node = new Node(value);
if (this.head === null) {
this.head = node;
} else {
let currentNode = this.head;
while (currentNode.next) {
currentNode = currentNode.next;
}
currentNode.next = node;
}
this.length++;
}
【问题讨论】: