双链表混乱

Double linked list confused

本文关键字:混乱 链表      更新时间:2023-10-16

我在理解这段代码时遇到了一些麻烦。它工作得很好,但是我不明白它的某些部分。

给定的代码应该将文件添加到列表中。 但我感到困惑的部分是

fNext->fPrevious = &aNode

fNext = &aNode

第一部分是将值分配给fNext->fPrevious

但是第二部分不是将fNext写入&Node的值吗

在这种情况下,fNext->fPrevious 和 fNext 中的值不应该相同。

有人可以向我解释一下吗?我已经看过这些示例,但我理解双链表的概念,但我不理解这段代码。

也有人可以详细说明这部分吗

aNode.fPrevious = this.

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->fPrior和fNext之间的区别。两者都指向同一件事。

不,他们不是。是的,我们确实将fNext->fPrevious设置为&aNode。但是在我们fNext设置为&aNode之后,fNext不是我们设置fPrevious的节点,而是aNode。所以fNext->fPreviousaNode.fPrevious,这是this,而不是aNode

也许给所有这些节点命名并图形化地查看会有所帮助。在你打电话给append之前,你有这样的东西:

prev      this          next                   aNode
...   <-- fPrevious <-- fPrevious      NIL <-- fPrevious
fNext --> fNext     --> ...                    fNext     --> NIL

因此,首先您将aNode.fPrevious设置为thisaNode.fNext设置为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     --> ...
-------------------/

请注意,此时,thisaNode都认为next节点是他们的fNext

最后,我们通过fNext设置为&aNode来解决此问题:

prev      this          aNode         next
...   <-- fPrevious <-- fPrevious <-- fPrevious
fNext --> fNext     --> fNext     --> ...

现在aNode被正确插入到链表中,在thisnext之间,每个人都同意一切。