为什么在向链表添加新节点后,prev 节点设置为 Circular 而不是 _Node?

Why does the prev node become set as Circular instead of _Node after adding a new node to a linked list?

有谁知道为什么prev节点设置为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++;
  }

Main.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

这里 Circular 不是对象类型,这意味着 console.log 找到了对它正在打印的对象的引用,因此它停止了循环。 head.next.prev 仍然是 _Node 类型,但它是我们已经显示的 _Node 对象。

console.log(main()) 试图向您展示 head.next 是什么时,它会尽力而为。它发现 head.next 是 "Boomer" 项,它的 prev 值指向 head。因此,当它试图向您展示 head.next.prev 时,它发现它指向了它试图向您展示的对象(头部)。这是一个循环条件,因为如果它试图走得更远,它将再次开始显示 "Apollo",因此它会停止并输出“[Circular]”,让您知道它因此停止了。我会试着把它画出来:

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

如果它试图跟随 head.next.prev,它将再次回到 head 并处于无限循环中,它会检测到并停止。