当前位置: 代码迷 >> java >> 删除链表中的重复项(按升序排列)
  详细解决方案

删除链表中的重复项(按升序排列)

热度:37   发布时间:2023-07-26 14:32:55.0

我的代码适用于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);
    }
}
  • 我的输出:281386386957 1022 1216 1232 1364 1428 1428 1428 1428 1501 1953

  • 预期输出:281386957 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] [-128; 127] Java使用高速缓存存储数字,因此,如果高速缓存中有数字,它将重新使用该对象。 因此,引用==将起作用,因为它们引用的是同一对象。 另一方面,如果您使用大于127或小于-128 ,则它将不起作用,因为Java将在缓存范围之外创建其他对象。

  相关解决方案