【发布时间】:2014-10-30 06:49:29
【问题描述】:
我一直在使用 Java 在名为 MoveNode() 的链接列表中实现一个简单的 utility 函数。
MoveNode() 的主要目的是删除一个链表(源链表)的第一个节点,并将其添加到另一个链表(目标链表)的开头。
示例如下:
Destination_Linked_List = {1,2,3}
Source_List_List = {4,5,6}
调用MoveNode(Destination_Linked_List,Source_List_List)后我们得到:
Destination_Linked_List = {4,1,2,3}
Source_List_List = {5,6}
以下是我对上述的Java实现:
static void MoveNode(LinkedList LL1,LinkedList LL2)
{
Node sourceref = LL2.head;
Node destref = LL1.head;
Node temp = sourceref.next;
sourceref.next = destref;
LL1.head = sourceref;
LL2.head = temp;
}
完美运行!!
但如果我更改代码的最后两行并将其替换为本地 Node 变量,则输出将完全改变。
这里是:
如果我改变:
LL1.head = sourceref;
LL2.head = temp;
到:
destref = sourceref;
sourceref = temp;
我通过执行此更改得到的输出是:
Destination_Linked_List = {1,2,3}
Source_List_List = {4,1,2,3}
这个异常背后的原因是什么?为什么列表的头节点没有正确更新?我错过了什么?
附: - head 节点是一个全局变量,可以从任何函数访问。
【问题讨论】:
标签: java data-structures linked-list singly-linked-list