Kodewick
Start learning →
Linked lists: nodes and pointers9 / 52

Linked lists: nodes and pointers

Lesson 9 of 52 · Part 2 · Arrays and linked lists · about 15 minutes

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.

3a
nullptr
One node: val holds 3, next holds nullptr (nothing comes after it)
Choose one

What does the last node’s next hold?

Choose one

What if the node were struct Node { int val; Node next; }; (next is not a pointer)? Would that work?

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

0x5a403Node
0x5a107Node
0x5a909Node
Three nodes scattered on the heap, linked into 3 → 7 → 9 by the addresses in next

(Each box is a node; its next holds the next node's address, and head holds the first one's.)

main.cpp
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}
Output
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.

Guess the outputA wrong guess is fine

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}
Put in orderDrag, or use the arrows

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.

  1. Node* b = new Node(7, c);
  2. Node* a = new Node(3, b);
  3. Node* c = new Node(9);
Should print
3 7 9

Walking: p = p->next until nullptr

Walking a whole list is nearly always this one for:

p↓
3a
7b
9c
nullptr

Walking: p starts at head, p = p->next each time, stops at nullptr
main.cpp
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}
Output
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.

Guess the outputA wrong guess is fine

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}
Fill inTap one to fill a blank; tap a blank to take it back

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}
Exercise 1

How long is the list

Complete length: walk from head to nullptr and count the nodes.

It should print
4
exercise1.cpp
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}
Output
Press Run or Ctrl+Enter

Length and search both walk

A linked list has no index: to get the i-th, you count from head.

OperationArray / vectorLinked list
Get the i-thO(1)O(n): walk i steps from the head
LengthO(1) (size is kept)O(n): walk and count (unless you keep it too)
Find a valueO(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).

The same 3 7 9 4: the array above sits cell after cell from 0x1000; the linked list's 4 nodes below are scattered over the heap, each next pointing at the following one, the last one NULL

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.

Choose one

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?

Choose allPick all that apply

A singly linked list that keeps only head. Which of these take O(n)? (You can pick more than one.)

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

3Node
7Node
9Node

Freeing the whole list: each round, save the next one in next, then delete the current one; in step 2 head turns red, meaning "given back, must not be read"

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.

main.cpp
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}
Output
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.

Choose one

Does this free the whole list correctly? for (Node* p = head; p != nullptr; p = p->next) delete p;

Exercise 2

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.

It should print
3
exercise2.cpp
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}
Output
Press Run or Ctrl+Enter

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.

main.cpp
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}
Output
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.

Operationvectorlist
Get the i-thv[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 backO(n), contiguous memory, fastO(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.

Choose one

list<int> lst = {3, 7, 9}; Which of these gets the second element, 7?

Summary

Take-away

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 << " ";