|
| 1 | +# Linked List |
| 2 | + |
| 3 | +## Singly Linked List |
| 4 | + |
| 5 | + |
| 6 | + |
| 7 | +The image seems self-explanatory, buuuuuuut... It is even more than that! |
| 8 | + |
| 9 | +Linked lists could be an alternative to arrays, but why exactly it would be better than it? |
| 10 | + |
| 11 | +Of course the answer is **IT DEPENDS**, but let's first see some of the differences between them: |
| 12 | + |
| 13 | +### Arrays |
| 14 | +- **Fixed Size**: Traditional arrays have a fixed size defined at the time of their creation. Resizing an array (e.g., increasing its capacity) typically involves creating a new array and copying all elements, which can be inefficient. |
| 15 | +- **Dynamic Arrays**: While some languages offer dynamic arrays (like Python’s lists or Javascript’s ArrayList), they still handle resizing behind the scenes, which can incur performance overhead. |
| 16 | +- **Insertion/Deletion Cost**: Adding or removing elements, especially in the middle of the array, requires shifting subsequent elements, leading to O(n) time complexity for these operations. |
| 17 | +- **Contiguous Memory**: Arrays require contiguous memory blocks, which can be a limitation in systems with fragmented memory or when dealing with very large datasets. |
| 18 | + |
| 19 | +### Linked Lists |
| 20 | +- **Dynamic Size**: Linked lists can easily grow and shrink by adding or removing nodes without the need to allocate or deallocate large blocks of memory. |
| 21 | +- **Efficient Memory Usage**: They use memory more efficiently when the number of elements fluctuates frequently. |
| 22 | +- **Constant Time Operations**: Once you have a reference to the node (e.g., during traversal), inserting or deleting a node can be done in O(1) ~~(but sometimes it depends haha)~~ time by adjusting the pointers. |
| 23 | +- **No Shifting Needed**: There's no need to shift elements, making linked lists more efficient for frequent insertions and deletions. |
| 24 | + |
| 25 | +So, now you might be thinking - "This sounds so much better, why not apply it to every situation?" |
| 26 | + |
| 27 | + |
| 28 | + |
| 29 | +hmm... Actually |
| 30 | + |
| 31 | +Stick with arrays unless you have a specific reason to use a linked list (like constant insertions/deletions). |
| 32 | +Arrays are fast, flexible, and optimized for most cases. |
| 33 | + |
| 34 | +If you need a linked list, you’ll have to implement it manually, which adds complexity you might not need. |
| 35 | + |
| 36 | +In short, arrays are your go-to in most situations, and linked lists are for special cases! |
| 37 | + |
| 38 | + |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | + |
0 commit comments