How is LinkedList's add(int, E) of O(1) complexity?

前端 未结 4 489
[愿得一人]
[愿得一人] 2020-12-29 20:54

From the linked-list tag wiki excerpt:

A linked list is a data structure in which the elements contain references to the next (and optionally the pr

相关标签:
4条回答
  • 2020-12-29 21:33

    Well, they do support constant-time inserts at arbitrary positions – but only if you happen to have a pointer to the list entry after which or in front of which you want to insert something. Of course, this won't work if you just have the index, but that's not what you usually do in optimized code.

    In Java, you can do that, too, but only using a list iterator.

    This property of linked lists is their biggest advantage compared to arraylists or so – for example, if you want to remove a user from the user list of a chatroom, you can store a pointer to the user's position in the userlist in the user so that, when he wants to leave the room, that can be implemented as a O(1) operation.

    0 讨论(0)
  • 2020-12-29 21:37

    This is because the article that you are reading considered "getting to that index" as a separate operation. The article assumes that you are already at the index you wish to perform add(int, E).

    To conclude:

    Insert or Remove operation = O(1)

    Finding node at nth index = O(n)

    0 讨论(0)
  • 2020-12-29 21:43

    The wiki page you quote says:

    O(1) insert and removal at any position

    Then you ask:

    I was surprised to read this – how can the list insert at a random index

    Herein lies the confusion: the terms position and index are not being used to mean the same thing. The wiki talks about an iterator or a pointer, not about an index.

    0 讨论(0)
  • 2020-12-29 21:46

    The operation of linking the new node to any node is O(1) but the operation of finding (helps to the loop) the concerned index is definitely O(n).

    There is no magic ;)

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