Removing from Doubly LinkedList in O(1)

喜夏-厌秋 提交于 2019-12-11 12:47:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!