Why does linked list delete and insert operation have complexity of O(1) ? shouldn't it be of O(n)

后端 未结 5 1981
情歌与酒
情歌与酒 2021-02-04 03:00

It is said that the complexity of the LinkedList remove and the add operation is of O(1). and in case of ArrayList it is of O(n).

5条回答
  •  被撕碎了的回忆
    2021-02-04 03:17

    Remove and the add operations are said to be of O(1) in case of LinkedList as, in LinkedList the shift is not involved, but there is traverse operation involved right?

    Adding to either end of a linked list does not require a traversal, as long as you keep a reference to both ends of the list. This is what Java does for its add and addFirst/addLast methods.

    Same goes for parameterless remove and removeFirst/removeLast methods - they operate on list ends.

    remove(int) and remove(Object) operations, on the other hand, are not O(1). They requires traversal, so you correctly identified their costs as O(n).

提交回复
热议问题