简体   繁体   中英

How to efficiently remove an element from java LinkedList

I have an algorithm where I pass through nodes in a graph in a certain way, occasionally passing through the same node several times, and I need to form a list of the nodes passed, such that a node appears once for the last time I passed it.

For instance, if I passed through nodes A -> B -> C -> A -> C , the list I need in the end is [B, A, C] .

What I wanted to do was to use a LinkedList, such that every node in the graph will contain a reference to its node in the LinkedList. Then, every time I pass through a node, I will remove its corresponding node from the LinkedList and insert it again into the end of the LinkedList, and the complexity of the operation will only be O(1) .

However, when I began implementing this, I ran into a problem: apparently, the java class LinkedList does not allow me to see its actual list nodes. Using the regular remove functions of LinkedList to remove the list node containing a given graph node will be O(n) instead O(1) , negating the whole point of using a LinkedList to begin with.

Naturally, I can implement LinkedList myself, but I would rather avoid that - it seems to me that if I have to implement LinkedList in java, I'm doing something wrong.

So, is there a way to solve this problem without implementing LinkedList on my own? Is there something that I'm missing?

As it seems, you are expecting a built-in approach, i don't think there is any Collection which provides such functionality. You will have to implement it on your own as @MartijinCourteaux suggested. Or:

  • use Sorted Set collection like TreeSet<E> with supporting cost of O(log n) for operations: add, remove and contains .
  • LinkedHashSet<E> But beware unlike HashSet<E> , LinkedHashSet can have O(1) expected performance for operations: add, contains, remove but the performance is likely to be just slightly below that of HashSet , due to the added expense of maintaining the linked list. But we can use it without incurring the increased cost associated with TreeSet . However, insertion order is not affected if an element is re-inserted into the set so try removing the first insertion of an element before re-inserting it .

LinkedHashMap keeps order of entered values and allows remove node by its key and then put back to the end. I think that it is all you need.

Unless your linked list is large just using a regular array list will give fast performance even with the shuffling. You should also consider using hash sets, if order is not important, linked hash set if the order of insert matters, or tree set if you want it sorted. They don't allow duplicate values but have good O performance for insert, delete and contains.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM