首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >javascript -简单链接列表遍历问题

javascript -简单链接列表遍历问题
EN

Stack Overflow用户
提问于 2021-01-06 14:07:01
回答 2查看 35关注 0票数 2

我使用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();

但是遍历方法从不打印最后一个元素。我在这里错过了什么?不过,insertAtTail方法看起来是正确的。有谁能告诉我。

谢谢

EN

Stack Overflow用户

发布于 2021-01-06 14:12:33

traversecurrent.nextElementnull时停止循环--但是在那个时候,current仍然是一个带有data的节点,只是在它之后没有一个next节点。

相反,继续前进,直到节点本身是null

代码语言:javascript
复制
traverse() {
  let current = this.head;
  while (current) { // *** Only change is on this line
    console.log("node data", current.data);
    current = current.nextElement;
  }
}

(那

代码语言:javascript
复制
while (current) {

可能是

代码语言:javascript
复制
while (current !== null) {

如果你愿意的话。

活生生的例子:

代码语言: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) {
      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();

票数 2
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65597271

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档