为什么要保留“上一个”?删除链表中的重复项时?
我想知道是否有人可以解释使用“LinkedListNode previous”变量的目的是什么。我了解尝试删除重复项的总体思路。您查看链表,如果某个值不在哈希表中,则将其插入。但如果是的话,它在做什么?我不太确定。
非常感谢您的帮助!如果有人能以清晰易懂的方式解释它,我将不胜感激。谢谢!
public static void deleteDups(LinkedListNode n) {
Hashtable table = new Hashtable();
LinkedListNode previous = null;
while (n != null) {
if (table.containsKey(n.data)) previous.next = n.next;
else {
table.put(n.data, true);
previous = n;
}
n = n.next;
}
}
i was wondering if anyone could explain what is the purpose of using the 'LinkedListNode previous' variable. i understand the general idea of trying to remove the duplicate. you look through the linked list, and if a value is not in the hashtable, insert it. but if it is, what is it doing? im not really sure.
thanks a bunch for helping! i would greatly appreciate it if someone could explain it in a clear and easy to understand way. thanks!
public static void deleteDups(LinkedListNode n) {
Hashtable table = new Hashtable();
LinkedListNode previous = null;
while (n != null) {
if (table.containsKey(n.data)) previous.next = n.next;
else {
table.put(n.data, true);
previous = n;
}
n = n.next;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果没有“前一个”,链表 cons 链如何保持连接?
想象一下:如果要将
Current
项变为Prev->Current->Next
,则需要将其转换为Prev->Next
从列表中删除。如果Prev
没有临时保存,则无法对其进行突变以更新链接。 (如果列表是双向链接列表,则不需要Prev
因为它可以从Current->previous
恢复)。快乐编码。
回应评论中的问题:
如果不采取任何措施,则重复项目不会从列表中断开连接。
n = n.next
更改n
的值(但不会更改存储在n
或其他位置的元素/节点的数据,因此 < code>Prev.next 从未从Current
更改)。需要做的是
Prev
的next
,被删除元素之前的元素/节点,必须更新为引用已删除元素之后的元素 (Next
)。(这也可以用函数式非突变风格编写,其中原始列表不会被修改,并且会构建一个新列表 - 在这种情况下,就不需要
Prev
)。Without the "previous", how would the linked-list cons chain remain connected?
Imagine:
Prev->Current->Next
which needs to be turned intoPrev->Next
if theCurrent
item is to be removed from the list. IfPrev
wasn't saved temporarily then it couldn't be mutated to update the linking. (If the list was a doubly-linked list thenPrev
wouldn't be needed because it could be restored fromCurrent->previous
).Happy coding.
In response to question in comment:
If nothing is done then the duplicate item is not disconnect from the list.
n = n.next
changes the value ofn
(but does not change the data of the element/node stored inn
or elsewhere soPrev.next
is never changed fromCurrent
).What needs to be done is the the
next
ofPrev
, the element/node before the deleted element, must be updated to refer to the element (Next
) after the deleted element.(This could also be written in a functional non-mutative style where the original list is not modified and a new list is built -- in that case there would be no need for
Prev
).