为什么在链接列表中添加一个新节点后,prev节点会被设置为循环而不是_Node?

问题描述 投票:0回答:1

有谁知道为什么前一个节点会被设置为 Circular 而不是 _Node?

我试图在链接列表的末尾添加一个新节点。我期待的是 prev 将要 _Node. 相反,它被设置为 Circular. 在这个练习之前,我看到 prev 被设定为 Circular我不知道循环链接列表的存在。

Console.log

LinkedList {
  head: _Node {
    value: 'Apollo',
    next: _Node { value: 'Boomer', next: [_Node], prev: [Circular] },
    prev: null
  },
  size: 6
}

LinkedList.js

const _Node = require("./Node");

class LinkedList {
  constructor() {
    this.head = null;
    this.size = 0;
  }

  insertFirst(item) {
    if (this.head !== null) {
      const newHead = new _Node(item);
      let oldHead = this.head;

      oldHead.prev = newHead;
      newHead.next = oldHead;
      this.head = newHead;
    } else {
      this.head = new _Node(item, this.head);
    }

    this.size++;
  }

  insertLast(item) {
    if (!this.head) {
      this.insertFirst(item);
    } else {
      let tempNode = this.head;
      while (tempNode.next !== null) {
        tempNode = tempNode.next;
      }
      // *** I have no idea why prev becomes [Circular] ***
      tempNode.next = new _Node(item, null, tempNode);
    }
    this.size++
  }

  insertAt(item, index) {
    if (index > 0 && index > this.size) {
      return;
    }

    if (index === 0) {
      this.insertFirst(item);
      return;
    }

    const newNode = new _Node(item);
    let currentNode = this.head;
    let previousNode = this.head;

    currentNode = this.head;
    let count = 0;

    while (count < index) {
      previousNode = currentNode;
      currentNode = currentNode.next;
      count++;
    }
    previousNode.next = newNode;
    newNode.next = currentNode;
    this.size++;
  }

Node.js

const LinkedList = require("./LinkedLists");

function main() {
  let SLL = new LinkedList();

  SLL.insertFirst("Apollo");
  SLL.insertLast("Boomer");
  SLL.insertLast("Helo");
  SLL.insertLast("Husker");
  SLL.insertLast("Starbuck");
  SLL.insertLast("Tauhida");

  return SLL;
}

console.log(main());

module.exports = main

Node.js

class _Node {
  constructor(value, next, prev) {
    this.value = value;
    this.next = next || null;
    this.prev = prev || null;
  }
}

module.exports = _Node
javascript linked-list singly-linked-list
1个回答
1
投票

这里是 Circular 不是对象类型,这意味着 console.log 找到了它要打印的对象的引用,所以它停止了进一步的循环。循环中停止继续前进。head.next.prev 尚属 _Node 但这是 _Node 我们已经显示的对象。

console.log(main()) 试图告诉你什么是 head.next 是,它尽其所能。它的发现是 head.next 是 "博美 "项目,其 prev 价值指向 head. 所以当它试图向你展示 head.next.prev 它看到它指向了它试图向你显示的对象(头部)。这就是一个循环的条件,因为如果它试图再往前走,就会再次开始显示 "阿波罗",所以它停下来,并输出"[循环]"让你知道它因为这个原因而停下来。 我试着把它画出来。

_Node: Apollo  <----------+  // this is the circular part
       next: Boomer  -+   |
       prev: null     |   |
_Node: Boomer  <------+   |
       next: Helo         |
       prev: Apollo  -----+

如果它试图按照 head.next.prev 归根结底 head 又会陷入无限循环,它检测到并停止。

© www.soinside.com 2019 - 2024. All rights reserved.