Modifications to linked list involve two operations:
- locating the node to append the new node to
- actually appending the node, by changing the node pointers
In Linked List, the second operation is an O(1)
operation, so it is a matter of the cost of first operations.
When appending to the last node, naive implementations of linked list would result in O(n)
iteration time. However, good linked list libraries would account for the most common uses, and special case accessing the last node. This optimization would result into O(1)
retrieval of the last element, resulting in overall O(1)
insertion time to end.
As for the middle, your analysis is correct in that locating the node would also take O(n)
. However, some libraries expose a method that would take a pointer to where the new node should be inserted rather than the index (e.g. C++
list
). This eliminates the linear cost, resulting in over all O(1)
.
While insertion to the middle is usually thought of as O(n)
operation, it can be optimized to O(1)
in some cases. This is the opposite of array list, where the insertion operation itself (the second operation) is O(n)
, as all the elements in higher locations need to be relocated. This operation cannot be optimized.
For insertation
A naive implementation of a linked list would result in O(n)
insertion time. However, good linked list library writers would optimize for the common cases, so they would keep a reference to the last elements (or have a circular linked list implementation), resulting in a O(1)
insertion time.
As for insertion to the middle. Some libraries like that of C++
, has a suggested location for insertion. They would take a pointer to the list node, where the new one is be appended to. Such insertions would cost O(1)
. I don't think you can achieve O(1)
by index number.
This is apposed to an array list, where insertion to the middle forces reordering of all the elements higher than it, so it has to be an O(n)
operation.