简体   繁体   中英

Java delete node from linked list by reference

How do I efficiently remove a node from java's LinkedList by reference to an object, or to a specific node? using remove(object) uses a traversal over the whole list, as evidenced by the documentation: "removes the first element e such that (o==null ? e==null : o.equals(e))". Can I remove by specific reference to a node? I don't mind storing the reference to the node in the object itself. I can't use the index of the list, as it may change. If not, is there another data structure which would allow me to do this?

You may want to use a HashSet

Deletion, insertion are in general in constant time, as stated by the official API :

This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets

If you decide to use a HashSet , don't forget to override both equals AND hashcode methods in your object.

Try using a LinkedHashSet . It's basically a HashSet with a deterministic ordering to its elements. Or alternatively, you can view it as a LinkedList backed with by an element look-up table.

I believe the remove(Object) operation will be constant-time.

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