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

时间:2020-06-10 05:37:25

标签: javascript linked-list singly-linked-list

有人知道为什么将上一个节点设置为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

1 个答案:

答案 0 :(得分:1)

此处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并处于无限循环中,它会检测并停止。

相关问题