Linked-List Efficiency
Insertion and deletion at the beginning of a linked list are very fast. They involve
changing only one or two references, which takes O(1) time.
Finding, deleting, or inserting next to a specific item requires searching through, on
the average, half the items in the list. This requires O(N) comparisons. An array is
also O(N) for these operations, but the linked list is nevertheless faster because
nothing needs to be moved when an item is inserted or deleted. The increased efficiency
can be significant, especially if a copy takes much longer than a comparison.
When would you use a linked list as opposed to an array as the implementation of a
stack or queue? One consideration is how accurately you can predict the amount of
data the stack or queue will need to hold. If this isn’t clear, the linked list gives you
more flexibility than an array. Both are fast, so speed is probably not a major
consideration.
Efficiency of Sorted Linked Lists
Insertion and deletion of arbitrary items in the sorted linked list require O(N)
comparisons (N/2 on the average) because the appropriate location must be found by
stepping through the list. However, the minimum value can be found, or deleted, in
O(1) time because it’s at the beginning of the list. If an application frequently
accesses the minimum item, and fast insertion isn’t critical, then a sorted linked list
is an effective choice. A priority queue might be implemented by a sorted linked list,
for example.
Insertion and deletion at the beginning of a linked list are very fast. They involve
changing only one or two references, which takes O(1) time.
Finding, deleting, or inserting next to a specific item requires searching through, on
the average, half the items in the list. This requires O(N) comparisons. An array is
also O(N) for these operations, but the linked list is nevertheless faster because
nothing needs to be moved when an item is inserted or deleted. The increased efficiency
can be significant, especially if a copy takes much longer than a comparison.
When would you use a linked list as opposed to an array as the implementation of a
stack or queue? One consideration is how accurately you can predict the amount of
data the stack or queue will need to hold. If this isn’t clear, the linked list gives you
more flexibility than an array. Both are fast, so speed is probably not a major
consideration.
Efficiency of Sorted Linked Lists
Insertion and deletion of arbitrary items in the sorted linked list require O(N)
comparisons (N/2 on the average) because the appropriate location must be found by
stepping through the list. However, the minimum value can be found, or deleted, in
O(1) time because it’s at the beginning of the list. If an application frequently
accesses the minimum item, and fast insertion isn’t critical, then a sorted linked list
is an effective choice. A priority queue might be implemented by a sorted linked list,
for example.