javascript - javascript - 简单的链表遍历问题
问题描述
我已经使用 javascript 实现了一个单链表。请在下面找到代码:
class Node {
constructor(data) {
this.data = data;
this.nextElement = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
isEmpty() {
return this.head === null;
}
insertAtHead(data) {
const tempNode = new Node(data);
tempNode.nextElement = this.head;
this.head = tempNode;
}
traverse() {
let current = this.head;
while (current.nextElement != null) {
console.log("node data", current.data);
current = current.nextElement;
}
}
insertAtTail(data) {
const tempNode = new Node(data);
if (this.head === null) {
this.head = tempNode;
return;
}
let currentNode = this.head;
while (currentNode.nextElement != null) {
currentNode = currentNode.nextElement;
}
currentNode.nextElement = tempNode;
}
}
const linkedList = new LinkedList();
linkedList.insertAtTail(12);
linkedList.insertAtTail(23);
linkedList.insertAtTail(25);
linkedList.traverse();
但是 traverse 方法从不打印最后一个元素。我在这里想念什么?虽然 insertAtTail 方法看起来是正确的。谁能告诉我。
谢谢
解决方案
traverse
current.nextElement
当is时停止它的循环null
——但在那一点上,current
它仍然是一个带有 的节点data
,只是它后面没有下一个节点。
相反,继续前进,直到节点本身是null
:
traverse() {
let current = this.head;
while (current) { // *** Only change is on this line
console.log("node data", current.data);
current = current.nextElement;
}
}
(那
while (current) {
可能
while (current !== null) {
如果你更喜欢。)
现场示例:
class Node {
constructor(data) {
this.data = data;
this.nextElement = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
isEmpty() {
return this.head === null;
}
insertAtHead(data) {
const tempNode = new Node(data);
tempNode.nextElement = this.head;
this.head = tempNode;
}
traverse() {
let current = this.head;
while (current) {
console.log("node data", current.data);
current = current.nextElement;
}
}
insertAtTail(data) {
const tempNode = new Node(data);
if (this.head === null) {
this.head = tempNode;
return;
}
let currentNode = this.head;
while (currentNode.nextElement != null) {
currentNode = currentNode.nextElement;
}
currentNode.nextElement = tempNode;
}
}
const linkedList = new LinkedList();
linkedList.insertAtTail(12);
linkedList.insertAtTail(23);
linkedList.insertAtTail(25);
linkedList.traverse();
推荐阅读
- java - org.eclipse.jdi.internal.connect.ConnectorImpI$StringArgumentImpI。
(洛格/日食/jdi - apache - Apache Proxypass 将代理端口与 HTTP 请求一起附加
- angular - 如何在 SeatMap anychart 中以编程方式选择座位?
- python - Matplotlib:带有变量的图例条目
- chart.js - Chart.js 将 x 轴标签向右移动
- android - 如何使用 recylerview 适配器中的共享首选项保存喜欢和不喜欢 imageview 按钮的状态,如 instagram
- vue.js - 在 Vue JS 中的组件内自动导入组件
- java - com.googlecode.javacv.FrameGrabber$Exception: cvCreateCameraCapture() 错误:无法创建相机捕捉
- docker - 关于为新容器应用 docker 命名卷的奇怪问题
- docker - 在 CircleCI 工作流或作业之后触发 Github Action