编辑
我决定使用 HashSet 来代替,因为它的复杂度是 O(N)。但是,我仍然有一个问题,它没有删除所有重复的数字,10 13 11 11 12 11 10 12 11。 它返回:10 13 11 12 10 11
static void removeDups(Node node) {
HashSet<Integer> values = new HashSet<Integer>();
Node previous = null;
while(node != null) {
if(values.contains(node.data))
previous.next = node.next;
else
values.add(node.data);
previous = node;
node= node.next;
}
}
不相关
我试图从链接列表中删除重复的元素,但由于某种原因,它不会删除最后一个重复元素。例如,如果列表是 10,11,12,11,12,9,11,则返回:10,11,12,9,11。 public static void removeDups1(Node head){
if(head == head.next)
head = head.next.next;
Node fastptr =head;
Node slowptr = head;
while(slowptr.next != null && fastptr.next.next !=null) {
if(slowptr.data == fastptr.data) {
fastptr.next = fastptr.next.next;}
slowptr = slowptr.next;
fastptr = fastptr.next;
}}
最佳答案
检查 fastptr.next.next == null
会提前退出循环。
关于java - 从链表中删除重复元素 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47047307/