3

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?

2
  • Essentially you want a pointer for your nodes? Commented Mar 28, 2014 at 20:35
  • Your own linked list? A built-in LinkedList? If your own it depends on how you implemented it. What have you tried? Can you post relevant code, and describe the issue you are having? As for other data structures, it depends on your requirements. You have to be more specific. Commented Mar 28, 2014 at 20:36

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this is very close to what I want. However, hashing still seems like a workaround, when I would like to access directly by reference.
HashSet does not allow duplicates. You may want define your equals and hashCode method keeping that in mind. You also need to take care of initial capacity if interation performance is critical
2

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.

2 Comments

I did consider a HashSet, but I need to preserve insertion order. Plus, hashing seems like a workaround, when I would like to access directly by reference.
in that case, as answered by @tskuzzy you'll need a LinkedHashSet. But hashing is not "a workaround"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.