c++ - 双链表混淆
问题描述
我在理解这段代码时遇到了一些麻烦。它工作得很好,但是我不明白它的某些部分。
给定的代码应该将文件添加到列表中。但我感到困惑的部分是
fNext->fPrevious = &aNode
fNext = &aNode
第一部分是为 fNext->fPrevious 赋值
但是,第二部分不是将 fNext 的值写入 &Node
在这种情况下,fNext->fPrevious 和 fNext 中的值不应该相同。
有人可以向我解释一下。我看过这些例子,但我理解双链表的概念,但我不明白这段代码。
也有人可以详细说明这部分
aNode.fPrevious = 这个。
void DoublyLinkedNode<DataType>::append(Node& aNode)
{
aNode.fPrevious = this;
if (fNext != &NIL)
{
aNode.fNext = fNext;
fNext->fPrevious = &aNode;
}
fNext = &aNode;
}
DoubleLinkedNode 的构造函数是这样的。
template<class DataType>
DoublyLinkedNode<DataType>::DoublyLinkedNode(const DataType& aValue)
{
fValue = aValue;
fPrevious = &NIL;
fNext = &NIL;
}
解决方案
我目前感到困惑的是 fNext->fPrevious 和 fNext 之间的区别。两者都指向同一件事。
不,他们不是。是的,我们确实设置fNext->fPrevious
为&aNode
. 但是我们设置fNext
为之后&aNode
,fNext
不是fPrevious
我们设置的节点,而是aNode
。所以fNext->fPrevious
是aNode.fPrevious
,这是this
,不是aNode
。
也许给所有这些节点命名会有所帮助,并以图形方式查看它。在你打电话之前append
,你有这样的事情:
prev this next aNode
... <-- fPrevious <-- fPrevious NIL <-- fPrevious
fNext --> fNext --> ... fNext --> NIL
所以,首先你设置aNode.fPrevious
tothis
和aNode.fNext
to fNext
,所以它向后指向this
和向前指向next
:
prev this next aNode
... <-- fPrevious <-- fPrevious this <-- fPrevious
fNext --> fNext --> ... fNext --> next
然后你设置fNext->fPrevious
为&aNode
. 由于fNext
当前是该next
节点,因此您将next
' 的后向指针更改为指向aNode
:
prev this aNode next
... <-- fPrevious <-- fPrevious <-- fPrevious
fNext --> fNext \ fNext --> ...
-------------------/
请注意,此时,两者都this
认为aNode
节点next
是他们的fNext
.
最后,我们通过设置fNext
来解决这个问题&aNode
:
prev this aNode next
... <-- fPrevious <-- fPrevious <-- fPrevious
fNext --> fNext --> fNext --> ...
现在aNode
正确地插入到链表中,在this
和之间next
,每个人都同意一切。
推荐阅读
- python - 从文件中获取输入,文件行成对分组
- bash - mv 文件夹目标上的通配符
- apache-flink - apache flink operator 和 keyed state 如何与并行实例一起工作?
- javascript - 如何在 html 表格中启用可点击的新添加行?
- git - 为什么我总是收到错误“推送到源/主服务器被拒绝”?
- django - 检查空字段的验证器
- javascript - 在锚元素上反应传递事件和参数
- javascript - Javascript将对象添加到数组
- android - 在我的代码中未使用时解组错误
- c# - 具有 Vector2Int 类型键的 JsonConvert 字典