In Java, why is insertion or deletion in a Linked List a constant time operation? Isn't it misleading?

前端 未结 4 1213
盖世英雄少女心
盖世英雄少女心 2021-01-04 09:43

Insertion or deletion of an element at a specific point of a list, assuming that we have a pointer to the node already, is a constant-time operation. - from

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-04 10:40

    First of: the LinkedList implemented in the Sun JDK effectively has a link to the last element as well as to the first element (there's only a head entry, but head.previous points to the last element). This means that even in the worst case navigating through a list to an element indicated by an index should take n/2 operations. It's also a doubly linked list.

    Apart from that: inserting into the beginning or end of a LinkedList is trivially O(1), because you don't need to traverse all elements.

    Inserting/removing anywhere else depends on how exactly you do it! If you use an Iterator (of a ListIterator for adding) then the operation can be O(1) as well, as the Iterator will already have a reference to relevant entry.

    If, however, you are using add(int, E) or remove(int), then the LinkedList will have to find the relevant entry (O(n)) and then remove the element (O(1)), so the entire operation will be O(n).

提交回复
热议问题