gpt4 book ai didi

Java引用和修改链表

转载 作者:行者123 更新时间:2023-12-01 12:42:17 25 4
gpt4 key购买 nike

我对 Java 有点陌生,目前关于引用的一件事让我有点困扰。

我有一个返回void的方法。我向这个方法传递了一个链表。还有另一个名为 noDuplicateLL 的链表变量引用同一个链表。 noDuplicateLL 跳过链表中的节点。

代码:

public static void removeDuplicate(LinkedListNode a) {
LinkedListNode noDuplicateLL = null;
if (a == null) {
//return null;
} else {
HashMap<Integer, Boolean> duplicateCheck = new HashMap<Integer, Boolean>();
while (a != null) {
// check in hashtable O(1)
if (duplicateCheck.containsKey(a.data)) {
noDuplicateLL.next = a.next;
} else {
noDuplicateLL = a;
duplicateCheck.put(a.data, true);
}
// update
a = a.next;
}
}
}

LinkedListNode a 迭代整个列表。一旦 a 达到 nullLinkedListNode noDuplicateLL 就会停止移动。因此,一旦完成此方法,两个指针都指向列表中的其他位置,而不是前面。

下面的方法从头到尾打印列表。

public static void printLinkedList(LinkedListNode head) {
while (head != null) {
System.out.println(head.data);
head = head.next;
}
}

我的主要内容:

    LinkedListNode LL = LinkedList.randomLinkedList(nodeVal);
removeDuplicate(LL);
printLinkedList(LL);

当 LL 作为 a 传递到方法中时,为什么输出仍然从链表的开头到结尾打印?是不是因为a只是指向链表中的节点,而LL则维护了对链表前面的引用?

最佳答案

LL --> some head node
// invoke method
// LL's value bound to parameter a
a --> some head node
// method executes
a --> head's next
a --> that next's next
...
a --> null
// method exits

LL仍然指向原来的头节点。

Is it because a simply points to the nodes in the linked list while LL maintains the reference to the front of the linked list?

是的。阅读 this你尽快做。

关于Java引用和修改链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24986029/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com