问题
I know that's the time complexity to remove an element from doubly linkedlist is O(1) and it seems obvious and clear BUT what happens if we don't receive an element to remove it but the one which is wrapped by the element?
for example if we define a class Element to wrap a String (To provide pointer pointing to the next and previous element) , we can do the removal in O(1) if the method receives that element as input not the string !
if the remove method receives the string , it has to search through the list to find the corresponding element , right ? so the time complexity in this case would be O(n) , not O(1) anymore
class Element{
String content;
Element next;
Element previous;
}
class LinkedList{
...
public remove(String s){
//it has to first find the element corresponding to this String !
}
}
回答1:
You are exactly right.
Remove is considered O(1) (when you do remove(Element)), but usually this goes together with a find operation (i.e. remove(String) or remove(find(String))), which is O(n).
回答2:
This linked list (Circular, doubly linked list, how to manage the node to object relationship?) uses a very suspect method which inserts properties into the objects being added to the list. It makes removal O(1) without searching for the object, but at the risk of property name clashes and a performance penalty if you're adding primitive types to the list (they get boxed when the properties are added).
来源:https://stackoverflow.com/questions/16497978/removing-from-doubly-linkedlist-in-o1