Making a linked list unique

眉间皱痕 提交于 2020-01-24 08:50:33

问题


So I have the 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 (only containing one of the same number) so this one would be

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

the only issue that is occurring is that the remove() method deletes the first instance of a nodes value and the first occurances of a number are suppose to be kept and following instances are suppose to be deleted from the list. Without collections, hashmaps, or anything.

    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();
    }

回答1:


Throw it all in a LinkedHashSet which will keep the order preserved and only keep 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]



回答2:


If you aren't trying to make your own, try using a Set. It's a generic collection that contains only unique elements and will handle addition of new elements. If these new elements are already in the collection, they will not be added.

EDIT: If you are implementing your own version of unique linked list, try making an add function that checks if the new data is already contained in the list. If not, add the new data. If you contain your validation in a method like that, it may would be easier to add new elemts to it. You could even expand on that idea and make a function that takes in a list or array and calls that addItem method on the elements the list argument.




回答3:


You would want to target duplication at the time of entry, not at the time of removal.

Since I'm not sure of the code you have for insertion, I'll walk through the general flow:

  • Start at the head for all insertions. If it's null, insert it carte-blanche.
  • Otherwise, iterate down the chain of nodes.
  • If any of their data values equal the data you wish to insert, do not insert it (ideally, return false).
  • Otherwise, continue iterating down the chain and insert it at the end. Return true.


来源:https://stackoverflow.com/questions/22822396/making-a-linked-list-unique

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!