【发布时间】:2017-10-07 22:20:23
【问题描述】:
我无法理解以下此方法如何删除链接列表中的重复项。调用此方法后,成功删除所有重复项。为什么头部不为空?头节点不会为空,因为方法中的当前变量迭代到最后。此方法如何成功更新列表以消除重复项?
static void removeDuplicate(node head)
{
// Hash to store seen values
HashSet<Integer> hs = new HashSet<>();
node current = head;
node prev = null;
while (current != null)
{
int curval = current.val;
// If current value is seen before
if (hs.contains(curval)) {
prev.next = current.next;
} else {
hs.add(curval);
prev = current;
}
current = current.next;
}
}
【问题讨论】:
-
如果用户回答了您的问题,请同时接受他的回答 (Accepting Answers: How does it work?)。如果不是,请说明什么仍未得到答复,这是 StackOverflow 的一个非常重要的部分,非常感谢。
标签: java data-structures linked-list