Linked lists: nodes and pointers
A singly linked list chains nodes made with new, each holding a value and a next pointer; you walk it with p = p->next until nullptr, so reaching the i-th is O(n), and the STL has std::list.
A vector needs one block of memory, and inserting or deleting in the middle moves everything after it. A linked list does it differently: each element is made on its own with new, anywhere on the heap, and each one remembers "where the next one is". In this lesson you build a singly linked list in C++, look closely at nodes, pointers, walking the list and delete, and finish with the STL's ready-made std::list.
A node: a value plus a pointer
Each item of a linked list is a node:
1struct Node {2 int val; // the number this node holds3 Node* next; // the next node's address; nullptr in the last one4 Node(int v, Node* n = nullptr) : val(v), next(n) {}5};
The struct holds a pointer to the same kind of struct. In C++ a struct's name can be used inside itself, with no struct Node * or typedef as in C. The constructor takes one more argument than the Node(int v) of the "Objects and pointers" lesson: Node(int v, Node* n = nullptr) fills in both members at once; the second has a default, so new Node(9) means "value 9, nothing after it". The null pointer in C++ is nullptr, not NULL.
What does the last node’s next hold?
What if the node were struct Node { int val; Node next; }; (next is not a pointer)? Would that work?
Node* next is fine.Made one by one with new
Each node is a block from new on the heap. Their addresses are whatever they are, not next to each other; next links them.
Stack
headNode*Heap
(Each box is a node; its next holds the next node's address, and head holds the first one's.)
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10// delete every node (the “delete it” step explains it)11void clear(Node* head) {12 while (head != nullptr) {13 Node* next = head->next;14 delete head;15 head = next;16 }17}18 19int main() {20 Node* c = new Node(9);21 Node* b = new Node(7, c);22 Node* a = new Node(3, b);23 Node* head = a;24 cout << head->val << " " << head->next->val << " " << head->next->next->val << "\n";25 clear(head);26 return 0;27}
3 7 9
Press Step and watch the three blocks appear on the heap one by one, linked by their nexts. head->next->next->val is two steps along the pointers. The folded clear gives the nodes back when you are done; every example in this lesson calls it.
To keep it short, these nodes live on the stack (a real list uses new). What does this program print?
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10int main() {11 Node c(9), b(7, &c), a(3, &b);12 Node* head = &a;13 cout << head->next->next->val - head->next->val << "\n";14 return 0;15}
head->next is the 7 node and head->next->next is the 9 node: 9 − 7 = 2. Each extra ->next follows the pointers one more step.Build 3 → 7 → 9 with new Node(v, next). Put these three lines in order: when a node is made, the node its next points to must already exist.
Node* b = new Node(7, c);Node* a = new Node(3, b);Node* c = new Node(9);
3 7 9
new Node(3, new Node(7, new Node(9))) goes in the same order: the innermost one is made first.Walking: p = p->next until nullptr
Walking a whole list is nearly always this one for:
p↓1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10// delete every node (the “delete it” step explains it)11void clear(Node* head) {12 while (head != nullptr) {13 Node* next = head->next;14 delete head;15 head = next;16 }17}18 19int main() {20 Node* head = new Node(3, new Node(7, new Node(9)));21 for (Node* p = head; p != nullptr; p = p->next)22 cout << p->val << " -> ";23 cout << "nullptr\n";24 clear(head);25 return 0;26}
3 -> 7 -> 9 -> nullptr
new Node(3, new Node(7, new Node(9))) is built from the inside out: first 9, then 7 pointing at 9, last 3 pointing at 7.
The loop condition is p->next != nullptr. What does it print?
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10int main() {11 Node c(9), b(7, &c), a(3, &b);12 int n = 0;13 for (Node* p = &a; p->next != nullptr; p = p->next)14 n++;15 cout << n << "\n";16 return 0;17}
p->next is already nullptr, so the loop stops and 9 is not counted: only 2. p != nullptr means "visit every node", p->next != nullptr means "stop on the last one"; both are common, pick the one you need. (These three nodes are local variables on the stack, not from new, so there is nothing to delete.)Pick what goes in the blank so p walks from node to node and adds up 3 + 7 + 9.
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10int main() {11 Node c(9), b(7, &c), a(3, &b);12 int sum = 0;13 for (Node* p = &a; p != nullptr; p = )14 sum += p->val;15 cout << sum << "\n";16 return 0;17}
next knows where the next node is: p = p->next. A list’s nodes are scattered in memory, so p + 1 doesn’t work the way it does in an array.How long is the list
✓Complete length: walk from head to nullptr and count the nodes.
4
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10int length(Node* head) {11 int n = 0;12 // p walks from head to nullptr13 return n;14}15 16int main() {17 Node* head = new Node(5, new Node(1, new Node(4, new Node(2))));18 cout << length(head) << "\n";19 while (head != nullptr) {20 Node* next = head->next;21 delete head;22 head = next;23 }24 return 0;25}
Length and search both walk
A linked list has no index: to get the i-th, you count from head.
| Operation | Array / vector | Linked list |
|---|---|---|
| Get the i-th | O(1) | O(n): walk i steps from the head |
| Length | O(1) (size is kept) | O(n): walk and count (unless you keep it too) |
| Find a value | O(n) | O(n) |
Where a linked list wins comes next lesson: once you are standing on a node, inserting or deleting after it is O(1).
Even with the same big O, an array often runs faster: when the CPU reads memory it reads a whole chunk at once (a cache line, usually 64 bytes). An array's next element has most likely come along; a linked list's next node is elsewhere, often another trip to memory. Each node also stores an extra 8-byte pointer, and new itself takes time.
The list is head → 5 → 1 → 4 → 2. p starts at head (on the 5). How many p = p->next until p is on the 4?
A singly linked list that keeps only head. Which of these take O(n)? (You can pick more than one.)
head = new Node(v, head): the new node’s next points at the old first node and head at the new one, also O(1).Done? delete it, in a destructor
Every node came from new, so each one must be deleted when you are done. The order matters: save next first, then delete. The other way round, delete p and then read p->next, reads memory that has already been given back.
Stack
headNode*nextNode*?Heap
Remembering to call clear every time is easy to forget. The C++ way is to wrap the list in a class and put this loop in its destructor ~List(): it runs by itself when the object goes out of scope, so nobody can forget it.
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10class List {11public:12 Node* head = nullptr;13 14 void push_front(int v) { head = new Node(v, head); }15 16 ~List() {17 int n = 0;18 while (head != nullptr) {19 Node* next = head->next; // save the next one first20 delete head; // then delete this one21 head = next;22 n++;23 }24 cout << "destructor: deleted " << n << " nodes\n";25 }26};27 28int main() {29 {30 List a;31 a.push_front(9);32 a.push_front(7);33 a.push_front(3);34 for (Node* p = a.head; p != nullptr; p = p->next)35 cout << p->val << " ";36 cout << "\n";37 } // a goes out of scope here: ~List() runs by itself38 cout << "main ends\n";39 return 0;40}
3 7 9 destructor: deleted 3 nodes main ends
A class like this must not be copied carelessly: List b = a; leaves two objects pointing at the same nodes, and when both are destroyed each node is deleted twice. To copy it, you write a copy constructor that copies the nodes one by one. The STL containers do all of this for you.
Does this free the whole list correctly? for (Node* p = head; p != nullptr; p = p->next) delete p;
p = p->next runs after delete p, so it reads a block that has been given back. On a normal computer it may happen to work, or it may crash; the engine here stops and tells you. Save next in a variable first, then delete.Give it all back
✓Complete delete_all: delete every node and return how many were deleted. Careful: after delete you can no longer read its next.
3
1#include <iostream>2using namespace std;3 4struct Node {5 int val;6 Node* next;7 Node(int v, Node* n = nullptr) : val(v), next(n) {}8};9 10int delete_all(Node* head) {11 int n = 0;12 // save the next one first, then delete the current one13 return n;14}15 16int main() {17 Node* head = new Node(5, new Node(1, new Node(4)));18 cout << delete_all(head) << "\n";19 return 0;20}
With the STL
The STL's ready-made linked list is std::list (header <list>). Inside it is a doubly linked list: one node per element holding the value, prev and next, each node allocated on the heap on its own and freed one by one in the destructor (more in two lessons). For one direction only there is also std::forward_list.
1#include <iostream>2#include <list>3#include <vector>4using namespace std;5 6int main() {7 list<int> lst = {3, 7, 9};8 vector<int> v = {3, 7, 9};9 10 for (int x : lst) // range for: front to back11 cout << x << " -> ";12 cout << "end\n";13 14 cout << v[2] << "\n"; // vector: the index gives the address in one step15 auto it = lst.begin(); // list: no lst[2], walk step by step16 ++it;17 ++it;18 cout << *it << "\n";19 20 cout << lst.size() << " " << lst.front() << " " << lst.back() << "\n";21 return 0;22}
3 -> 7 -> 9 -> end 9 9 3 3 9
std::list has no operator[] on purpose: getting the i-th is O(n), and writing lst[i] would make it look cheap. The iterator it is our hand-written p: ++it is p = p->next, *it is p->val.
| Operation | vector | list |
|---|---|---|
| Get the i-th | v[i]: O(1) | no [], walk i steps from begin(): O(n) |
front() / back() | O(1) | O(1) |
size() | O(1) | O(1) (kept since C++11) |
| Walk front to back | O(n), contiguous memory, fast | O(n), scattered nodes, slower |
In interviews: LeetCode's linked-list problems give you struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {} };, the same as this lesson's Node. They test hand-written pointers, so std::list is not allowed; in everyday code, when you want "a row of numbers", think vector first, and use list only for frequent inserts and deletes in the middle when you already have the position.
list<int> lst = {3, 7, 9}; Which of these gets the second element, 7?
std::list has no [], and its iterators can’t do + 1 either (only containers stored side by side, like vector, can jump ahead): they can only ++ one step at a time. next(it) is the iterator one step after it; next(it, k) takes k steps, one by one inside, so O(k).Summary
Linked lists: nodes scattered on the heap, linked by next
- Node = a value + the next node's address; the last one is nullptr
- Walking: for (p = head; p != nullptr; p = p->next)
- No index: getting the i-th and the length are O(n)
- Save next before delete; in a destructor you cannot forget
- std::list is the ready-made (doubly) linked list, with no []
1struct Node { int val; Node* next;2 Node(int v, Node* n = nullptr) : val(v), next(n) {} };3for (Node* p = head; p != nullptr; p = p->next)4 cout << p->val << " ";