有人知道为什么将上一个节点设置为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
答案 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
并处于无限循环中,它会检测并停止。