【发布时间】:2018-05-12 16:58:37
【问题描述】:
所以我有一个链接列表,我正在尝试从中删除重复项。
我想出的基本算法几乎是使用跑步者技术。我保留两个指针来比较相邻元素。如果它们相同,我将 p1 的指针更改为指向 p1.next.next,否则我继续遍历列表。但是,我在输入的解决方案中不断收到空指针异常。
Node RemoveDuplicates(Node head) {
// This is a "method-only" submission.
// You only need to complete this method.
if (head == null){
return null;
}
Node current = head;
Node runner = head;
while(current != null && runner != null && runner.next != null){
runner = runner.next;
if(runner.data == current.data){
if(current.next != null){
current = current.next.next;
}
}else{
current = current.next;
}
}
return current;
}
在我退出 while 循环时,电流为空。我认为这是问题所在。我将如何返回更改列表的头部。
【问题讨论】:
-
为什么不直接使用
Set来禁止重复?是否有必要在将项目插入您的收藏时保持它们的顺序? -
这是我最初的想法,使用一个集合,但已经排序了
-
并且输出看起来仍然是排序顺序
-
我通常在未排序的时候使用集合..但也许没关系
-
LinkedHashSet给您带来Set和List的好处怎么样?见LinkedHashSet in Oracle JDK 8 API
标签: java