从O(1)中的双向链表中删除

时间:2013-05-11 14:12:57

标签: data-structures linked-list time-complexity

我知道从双向链表中删除元素的时间复杂度是O(1)并且它看起来很明显但是如果我们没有收到要移除它的元素但是由元素包装的元素会发生什么?

例如,如果我们定义一个类Element来包装一个String(提供指向下一个和前一个元素的指针),如果方法接收该元素作为输入而不是字符串,我们可以在O(1)中进行删除!

如果remove方法接收到字符串,则必须通过列表搜索才能找到相应的元素,对吧?所以这种情况下的时间复杂度将是O(n),而不是O(1)

  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 !
    }
  }

2 个答案:

答案 0 :(得分:1)

你是完全正确的。

删除被视为O(1)(当您执行remove(Element)时),但通常这与查找操作(即remove(String)remove(find(String)))一起使用,即{{ 1}}。

答案 1 :(得分:0)

此链接列表(Circular, doubly linked list, how to manage the node to object relationship?)使用一种非常可疑的方法,该方法将属性插入到添加到列表中的对象中。它会在不搜索对象的情况下删除O(1),但是如果要将基本类型添加到列表中,则存在属性名称冲突和性能损失的风险(添加属性时它们会被装箱)。

相关问题