Java: best way to find and remove an element from linked list

Andi R :

I've been wondering about this for quite some time and haven't found a good answer to that yet on SO.

What I want to do is to find an element in a linked list and delete it immediately. If I constructed the linked list on my own, it would be easy, since Ijust traverse the doubly linked list:

-> N1 <-> N2 <-> N3 <-> N4 <-> N5 <-

and when you find e.g. N3, you change the node.previous and node.next pointers such that:

-> N1 <-> N2 <-> N4 <-> N5 <-

If the element in in the middle, this would require roughly n/2 steps.

Is there a proper approach to do this in java.util.LinkedList<Integer>?

An approach that is insufficient for me is:

Integer found = null;
for(Integer elem : list){
    if(hasCertainProperty(elem)){
        found = elem;
    } 
}
if(found != null){
    list.remove(found);
}

If the element is the middle element in the list (double linked list, so search from end of the list is theoretically possible if index is known) it would require a maximum of roughly n/2 + n/2 = n steps. Whereas in the self-made traverse it would only need n/2 steps.

I know those 2 and other approaches are in O(n), but you know, sometimes that n/2 makes a difference in practice.

Thanks for your help.

Median Hilal :

Java 8 will do this for you.

list.removeIf(x -> hasCertainProperty(x));

This internally loops through the list, checks for each item x whether it satisfies your condition hasCertainProperty, and removes the item. I guess you should not be concerned about the performance. Java will handle it for you.

Apart from that, you should use ListIterator which was exactly made for that purpose. You obtain it by using LinkedList#listIterator:

ListIterator<Integer> listIter = list.listIterator(0);
while (listIter.hasNext()) {
    Integer element = listIter.next();

    if (hasCertainProperty(element)) {
        listIter.remove();
        break;
    }
}

Its remove does not need any lookup, since it maintains a pointer to the node while iterating. So it has hands on the node you want to remove.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116091&siteId=1