有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从链表中删除重复元素

编辑

我决定使用HashSet,因为它是O(N)。然而,我仍然有一个问题,它没有删除所有重复的数字,10131111111111。 返回时间:1013111111

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;

   }}

共 (0) 个答案