Create a unique unique list

So I have a list:

 8,9,1,2,3,5,3,1,8,1,4,5,2,7,9,9,5,6

and want to reproduce it as unique (with only one number) so that this

8,9,1,2,3,5,4,7,6

The only problem that arises is that the remove () method removes the first instance of the node value, and it is assumed that the first numbers of the number should be preserved, and the following instances are supposed to be removed from the list. No collections, hashmaps or anything else.

    while(current.getPrevious() != null) {
        while(next.getPrevious() != null) {
            if(next.equals(current)){
                next = next.getNext();
                continue;
            }
            else if(next.getValue().compareTo(current.getValue()) == 0){
                remove(next.getValue()); // The remove method deletes the first instance of number in the linked list
                next = next.getNext();

            }
                next = next.getPrevious();

        }
        current = current.getNext();
        next = current.getNext();
    }
+4
source share
3 answers

Throw it all in LinkedHashSet, which will keep order and keep only the first copy.

Set<Integer> noDups = new LinkedHashSet<Integer>(myList);

Here is the result if you use your list with System.out.println(noDups);:

[8, 9, 1, 2, 3, 5, 4, 7, 6]
+3
source

, Set. , . , .

EDIT: , , , . , . , , . , , addItem .

+1

, .

, , :

  • . , -.
  • .
  • If any of their data values โ€‹โ€‹is equal to the data you want to insert, do not insert them (ideally, return false).
  • Otherwise, continue to repeat the chain and insert it at the end. Bring it back true.
0
source

Source: https://habr.com/ru/post/1534717/


All Articles