When would you use a linked list vs. a vector?
Vector :
- Vector is another name for dynamic arrays.
- It is the name used for the dynamic array data structure in C++.
- If you have experience in Java you may know them with the name ArrayList.
- (Java also has an old collection class called Vector that is not used nowadays because of problems in how it was designed.)
- Vectors are good for random read access and insertion and deletion in the back (takes amortized constant time).
- But bad for insertions and deletions in the front or any other position (linear time, as items have to be moved).
- Vectors are usually laid out contiguously in memory, so traversing one is efficient because the CPU memory cache gets used effectively.
Linked lists :
- Linked lists, on the other hand, are good for inserting and deleting items in the front or back (constant time).
- But not particularly good for much else.
- For example deleting an item at an arbitrary index in the middle of the list takes linear time because you must first find the node.
- On the other hand, once you have found a particular node you can delete it or insert a new item after it in constant time, something you cannot do with a vector.
- Linked lists are also very simple to implement, which makes them a popular data structure.
Comments
Post a Comment