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

问题描述 投票:0回答:1

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

[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?

当我们将两个节点设置为相同的点,并且如果我们更改一个节点以指向下一个不同的点,则另一个节点也将被更改。 但是,如果我们仅说NodeC = NodeB,似乎NodeA上没有任何变化。我为此一直在努力几天,谁能解释这是如何工作的?非常感谢!

algorithm data-structures linked-list singly-linked-list doubly-linked-list
1个回答
0
投票

当您说NodeA: 1->2->3;时,有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: 6->7->8;引用另一组节点Node6, Node7, Node8和一个变量NodeB = Node6

当您执行NodeC = NodeA时,现在有两个变量,每个变量都引用Node1。所以NodeC = NodeA = 1->2->3。希望到目前为止,这是有道理的。

[当您执行NodeC.next = NodeB时,就是说,对于变量NodeC(即Node1)引用的节点,将其next成员更新为变量NodeB所引用的节点(即[ C0])。

所以

Node6

所以NodeC = NodeA = Node1 // Variables NodeB = Node6 Node1 value = 1 next = Node6 。并且由于NodeC = 1->6->7->8也与NodeA引用相同的节点,因此NodeC

[当您执行NodeA also = 1->6->7->8时,NodeC = NodeB现在引用NodeC,并且Node6继续引用NodeA,因此对Node1的更改不会影响NodeC

© www.soinside.com 2019 - 2024. All rights reserved.