A chain of nodes
A linked list stores each item in its own node. A node holds a value and a pointer to the next node. The first node is the head; the last one points to nullptr.
Think of it like this: A treasure hunt: each clue tells you where the next clue is. You can't jump to clue 5 – you follow 1, 2, 3, 4.
#include <iostream>
using namespace std;
struct Node {
int value;
Node* next;
Node(int v) : value(v), next(nullptr) {}
};
int main() {
// build 10 -> 20 -> 30
Node* head = new Node(10);
head->next = new Node(20);
head->next->next = new Node(30);
for (Node* cur = head; cur != nullptr; cur = cur->next)
cout << cur->value << " -> ";
cout << "nullptr" << endl;
return 0;
}Output
10 -> 20 -> 30 -> nullptr
new Node(10)creates a node in memory and gives back its address (a pointer).head->nextmeans “thenextfield of the nodeheadpoints to”.
Array vs linked list
| Operation | vector | Linked list |
|---|---|---|
| get the i-th item | O(1) | O(n) – follow the links |
| add/remove at the front | O(n) | O(1) |
| add/remove after a node you have | O(n) | O(1) |
| memory | one block | a pointer in every node |
Tip: The standard library has
std::list(doubly linked) andstd::forward_list. Writing your own teaches you pointers – and interviews love linked list questions.