我的代码适用于 1 位和 2 位数字,但不适用于 > 2 位数字
public class remove_duplicates {
public static node<Integer> takeInput() {
Scanner s = new Scanner(System.in);
int data = s.nextInt();
node<Integer> head = null;
while (data != -1){
node<Integer> newNode =new node<Integer>(data);
if(head == null){
head = newNode;
}
else {
node<Integer> temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next =newNode;
}
data = s.nextInt();
}
return head;
}
public static node<Integer> removeDuplicates(node<Integer> head){
node<Integer> current = head;
while(current.next != null){
if(current.data == current.next.data){
current.next = current.next.next;
}
else
current = current.next;
}
return head;
}
public static void print (node<Integer>head){
node<Integer> temp = head;
while (temp != null)
{
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
node<Integer> head = takeInput();
node<Integer> data = removeDuplicates(head);
print(data);
}
}
我的输出:281 386 386 957 1022 1216 1232 1364 1428 1428 1428 1428 1501 1953
预期输出:281 386 957 1022 1216 1232 1364 1428 1501 1953
为什么它适用于 1/2 位整数而不适用于 3 位或更多数字?我该如何解决这个问题?
最佳答案
解决方案
使用equals()
。在 removeDuplicates
函数中,将 if(current.data == current.next.data)
行更改为以下内容: if(current.data.equals(current. next.data))
基本原理
您应该始终使用equals()
来比较两个对象的特定值,而不是==
。原因是 ==
比较对象引用,而 equals()
比较该对象的值。该值将取决于您的需求,您可以设置特定的比较标准,但对于像 Integer
这样的原生类型包装,它默认比较数字而不是对象地址 - 这是使用 ==
得到的 -.
为什么==
适用于一位/两位数字Integer
?
当Integer的值在[-128范围内时; 127]
Java 使用缓存来存储数字,因此如果缓存中有数字,它就会重新使用该对象。因此引用 ==
会起作用,因为它们引用的是同一个对象。另一方面,如果您使用大于127
或小于-128
的整数,则它将不起作用,因为Java将在缓存范围之外创建不同的对象。
关于java - 删除链表中的重复项(按升序排列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54654258/