Advantage
- Linked Lists are dynamic data structures, arrays are not
- It can allocate the needed memory in runtime
- Very efficient if we want to manipulate the first elements
- Can store items with different sizes; an array assumes every element to be exactly the same
- It is easier for a linked list to grow organically. An array’s size usually need to be known ahead of time or re-created when it needs to grow
Disadvantages
- Waste memory because of the references
- Nodes in a linked list must be read in order from the beginning as linked lists have sequential access (array items can be reached via indexes in O(1) time)
- Solution: doubly linked lists -> easier to read, but memory is wasted in allocating space for a back pointer
Pros & Cons of an array
- Pros
- We can use random access by indexes, O(1)
- Very fast implementation and use
- Very fast data structure
- A good choice when we want to add items over and over again and we want to get items with given indexes
- Cons
- Usually, we have to know the size of the array at compile time
- If it is full we have to create a bigger array and have to copy values one by one.
- It is not able to store items with different types (Not the case in Python)
Linked Lists vs Arrays
Linked Lists | Arrays | |
---|---|---|
search | O(n) | O(1) via index |
insert at the start | O(1) | O(N) |
insert at the end | O(N) | O(1) |
Waste Space | O(N) | 0 |
Implementation
Linked List implementation with Python
1 | class Node(object): |
Other Note
abstract data types | data structures |
---|---|
Stack | array, linked list |
Queue | array, linked list |
Priority queue | heap |
Dictionary / hashmap | array |