10
DSA + algorithms / Beginner
Arrays and linked lists
Static/dynamic arrays, vectors, nodes, singly linked lists, trade-offs, and practical implementation patterns.
01Arrays
An array stores elements contiguously, making indexed access fast and cache-friendly. Fixed arrays have a fixed size; dynamic arrays such as std::vector grow by allocating a larger region and moving/copying elements.
cppStatic and dynamic arrays
int fixed[4] = {10, 20, 30, 40};
std::vector<int> dynamic{10, 20, 30};
dynamic.push_back(40);
02What a node is
A linked-list node stores a value plus a link to another node. The nodes do not have to be contiguous in memory. This makes insertion/removal easy when you already have the correct link, but random indexing requires walking through nodes.
cppSingly linked nodes
struct Node {
int value;
Node* next;
};
Node third{30, nullptr};
Node second{20, &third};
Node first{10, &second};
03Trade-offs
| Operation | Dynamic array | Singly linked list |
|---|---|---|
| Index | O(1) | O(n) |
| Append | Amortized O(1) | O(1) with tail |
| Insert middle | O(n) shifts | O(1) after locating node |
| Cache locality | Excellent | Poorer |