如何在链表中指向/引用节点



我对节点在linkedlist中如何相互引用感到非常困惑。 假设我们有这样的代码:

NodeA: 1->2->3;

当我们设置两个节点时,如果我们将一个节点更改为下一个节点,另一个节点也会发生变化。但是,如果我们只说 NodeC = NodeB,那么 NodeA 似乎没有任何变化。我一直在为此而挣扎 几天,谁能解释一下这是如何工作的?真的很感激!

当你说Node6, Node7, Node8时,有 3 个节点被引用,还有 1 个变量:

// These are the nodes. They don't have names, I'm just calling them NodeX, where X is a number.
Node1
value = 1
next = Node2
Node2
value = 2
next = Node3
Node3
value = 3
next = null
// This is the variable
NodeA = Node1

然后,NodeB = Node6引用另一组节点,NodeC = NodeA和一个变量Node1

当你做NodeC = NodeA = 1->2->3时,现在有两个变量,每个变量都引用NodeC.next = NodeB。所以NodeA: 1->2->3; NodeB: 6->7->8; ListNode NodeC = NodeA; IF WE DO: NodeC.next = NodeB;// NodeC becomes 1->6->7->8, NodeA also changed to 1->6->7->8, why? OR WE DO: NodeC = NodeB;//this will only change NodeC, but NodeA stay the origin, why?0.希望到目前为止这是有意义的。

当你做Node1时,我们说,对于变量next引用的节点(即NodeB(,将其Node6成员更新为变量NodeC = 1->6->7->8引用的任何内容(即NodeA(。

所以

NodeC = NodeA = Node1 // Variables
NodeB = Node6
Node1
value = 1
next = Node6

所以NodeC.由于NodeA also = 1->6->7->8也引用了NodeC = NodeB所做的同一节点,因此NodeC.

当你执行Node6时,NodeA现在引用Node1,而NodeC继续引用NodeA,所以对CC_26的更改不会影响CC_27。

最新更新