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

前端 未结 4 1181
盖世英雄少女心
盖世英雄少女心 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:32

    You said it yourself: "assuming we have a pointer to the node already". That avoids the traversal you identify as the cause of the linear time.

    Admittedly, the Wikipedia text is a bit ambiguous, since there are two nodes involved: the one being inserted, and the one in the list where to insert it.

    0 讨论(0)
  • 2021-01-04 10:34

    You are missing the point I think here. It is just the INSERTION and DELETION that have a constant time not the finding the point of insertion or deletion as well! The time is constant because you simply need to set the references (links) to the previous and next item in the list -- whereas for instance with ArrayList, in the case of insertion you need to allocate memory for (at least) one more item and transfer the existing data into the newly allocated array (or with deletion you have to shift elements in the array around once you deleted the item).

    0 讨论(0)
  • 2021-01-04 10:37

    " assuming that we have a pointer to the node already, is a constant-time operation"

    You missed the first assumption, it seems.

    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题