Kodewick
Start learning →
Doubly linked and circular lists11 / 52

Doubly linked and circular lists

Lesson 11 of 52 · Part 2 · Arrays and linked lists · about 17 minutes

A doubly linked list gives each node a next and a prev pointer, so you can walk back, and inserting changes 4 pointers in order; a circular list's last node points to the first, and std::list is both, with a sentinel.

A singly linked list only goes forward: standing on a node, to find the one before it you walk from the head again. A doubly linked list gives every node one more pointer, to the one before; a circular list makes the last node point back to the first. In this lesson you write both by hand in C++, then look at the STL's std::list, which is exactly the two put together.

The doubly linked node

1struct DNode {2    int val;3    DNode* prev;   // the one before (textbooks often call it prior)4    DNode* next;   // the one after5    DNode(int v) : val(v), prev(nullptr), next(nullptr) {}6};

One more pointer costs 8 more bytes per node and buys this: from any node you reach both neighbours in O(1), and holding a node you can delete it without walking from the head to find the one before.

The first node’s prev and the last node’s next are both nullptr. Three nodes linked together look like this:

Three nodes of a doubly linked list: next points forward (solid), prev points back (dashed), and both ends are nullptr
Choose one

In a doubly linked list you are standing on node p. How long does it take to reach the node before it?

Inserting: 4 pointers, in the right order

Insert a new node s after p (with q after p so far). Four pointers change:

Doubly linked insert: 5 (s) goes between 3 (p) and 7 (q); the four pointers change in order 1 to 4, dashed lines are the old links
  1. s->next = p->next;: s links to q after it first
  2. p->next->prev = s;: q points back at s
  3. s->prev = p;: s points back at p
  4. p->next = s;: only now change p's forward pointer

The key is that step 4 comes after 1 and 2: both find q through p->next, and once p->next changes, q is lost. As with a singly linked list, it is still "link what comes after, then change what comes before".

p↓q↓
3a
5s
7b
nullptr

Inserting 5 (s) between 3 (p) and 7 (q): the box on each node's left is prev, the one on its right is next
main.cpp
1#include <iostream>2using namespace std;3 4struct DNode {5    int val;6    DNode* prev;7    DNode* next;8    DNode(int v) : val(v), prev(nullptr), next(nullptr) {}9};10 11void show(DNode* head) {12    for (DNode* p = head; p != nullptr; p = p->next)13        cout << p->val << " ";14    cout << "\n";15}16 17void clear(DNode* head) {18    while (head != nullptr) {19        DNode* next = head->next;20        delete head;21        head = next;22    }23}24 25int main() {26    DNode* p = new DNode(3);27    DNode* q = new DNode(7);28    p->next = q;29    q->prev = p;30 31    DNode* s = new DNode(5);32    s->next = p->next;          // 133    p->next->prev = s;          // 234    s->prev = p;                // 335    p->next = s;                // 436    show(p);37    // walk back: from q along prev38    for (DNode* r = q; r != nullptr; r = r->prev)39        cout << r->val << " ";40    cout << "\n";41    clear(p);42    return 0;43}
Output
3 5 7 
7 5 3 

(If p is the last node, p->next is nullptr and there is no q: step 2 needs if (p->next != nullptr) first. The folded clear deletes the nodes one by one along next.)

Put in orderDrag, or use the arrows

Put these 4 lines in order to insert s (node 2) after p (node 1), so the program prints 1 2 3 forwards and 3 2 1 backwards.

  1. s->next = p->next;
  2. s->prev = p;
  3. p->next->prev = s;
  4. p->next = s;
Should print
1 2 3
3 2 1
Exercise 1

Doubly linked: insert after p

Complete insert_after: insert x after p; there is always a node after p. Change the 4 pointers in order so the program prints the list forward and backward.

It should print
10 20 30
30 20 10
exercise1.cpp
1#include <iostream>2using namespace std;3 4struct DNode {5    int val;6    DNode* prev;7    DNode* next;8    DNode(int v) : val(v), prev(nullptr), next(nullptr) {}9};10 11void show(DNode* head) {12    for (DNode* p = head; p != nullptr; p = p->next)13        cout << p->val << " ";14    cout << "\n";15}16 17void clear(DNode* head) {18    while (head != nullptr) {19        DNode* next = head->next;20        delete head;21        head = next;22    }23}24 25void insert_after(DNode* p, int x) {26    DNode* s = new DNode(x);27    // 1 s->next  2 p->next->prev  3 s->prev  4 p->next28}29 30int main() {31    DNode* a = new DNode(10);32    DNode* b = new DNode(30);33    a->next = b;34    b->prev = a;35    insert_after(a, 20);36    show(a);37    for (DNode* r = b; r != nullptr; r = r->prev)38        cout << r->val << " ";39    cout << "\n";40    clear(a);41    return 0;42}
Output
Press Run or Ctrl+Enter

Deleting: both neighbours change

Delete the node q after p:

Doubly linked delete: 5 (q) between 3 (p) and 7 is taken out. Dashed lines are the four pointers that went through q; 1 makes 3 point forward straight at 7, 2 makes 7 point back straight at 3, both directions skip q, then free(q)
1DNode* q = p->next;2p->next = q->next;3if (q->next != nullptr)4    q->next->prev = p;5delete q;

Only 2 pointers change, then delete. Again, link everything up before you delete. (The picture's free(q) is delete q in C++.)

Guess the outputA wrong guess is fine

After deleting b, the node after a, what does it print?

1#include <iostream>2using namespace std;3 4struct DNode {5    int val;6    DNode* prev;7    DNode* next;8    DNode(int v) : val(v), prev(nullptr), next(nullptr) {}9};10 11int main() {12    DNode a(1), b(2), c(3);13    a.next = &b; b.prev = &a; b.next = &c; c.prev = &b;14    DNode* p = &a;15    DNode* q = p->next;16    p->next = q->next;17    q->next->prev = p;18    cout << a.next->val << " " << c.prev->val << "\n";19    return 0;20}
Choose one

The node q you are deleting is the last one (q->next is nullptr). Which line goes wrong if you don’t check first?

Circular lists: the last points back to the head

Change the last node's next from nullptr to the first node and you have a circular list. From any node you can walk through all of them.

head↓
3a
7b
9c
back to 3

A circular list: the last node's next points back to the first, no nullptr

Now a walk cannot wait for nullptr (it never comes); it waits until it is "back where it started":

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 10int main() {11    Node* c = new Node(9);12    Node* head = new Node(3, new Node(7, c));13    c->next = head;              // the last points back to the head14 15    Node* p = head;16    do {17        cout << p->val << " ";18        p = p->next;19    } while (p != head);         // stop when back at the start20    cout << "\n";21 22    c->next = nullptr;           // break the circle first, then delete one by one23    while (head != nullptr) {24        Node* next = head->next;25        delete head;26        head = next;27    }28    return 0;29}
Output
3 7 9 

It is do … while because p starts equal to head, so it must take a step before checking. Freeing needs care too: a plain while (head != nullptr) would go round the circle deleting forever, so break the circle first.

In practice a circular singly linked list often keeps no head, only a tail pointer rear (pointing at the last node): the first node is just rear->next, so inserting at the front and at the back are both O(1).

Singly linkedDoubly linkedCircular
Each nodeval, nextval, prev, nextas singly, the tail points back to the head
Holding node x, delete itO(n): find the one beforeO(1): it is x->prevO(n): go round to find the one before
Can it walk backnoyesno, but it comes round
Where a walk stopsp == nullptrp == nullptr (or a sentinel)p == head (back at the start)

A favourite exam question: an empty list is L->next == nullptr for a singly linked list with head node L, and L->next == L for a circular one; in the 4-step doubly linked insert, the last step is always changing p->next.

Guess the outputA wrong guess is fine

Swap the do … while for a plain while. What does this 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    c.next = &a;13    Node* head = &a;14    Node* p = head;15    int n = 0;16    while (p != head) {17        n++;18        p = p->next;19    }20    cout << n << "\n";21    return 0;22}
Choose one

How do you tell that a circular singly linked list L with a dummy head node is empty?

Choose one

A circular singly linked list without a dummy head keeps only the tail pointer rear. Which node is the first one?

Exercise 2

How many in the circle

Complete count: go once round from head and count the nodes (the list is not empty).

It should print
4
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 count(Node* head) {11    int n = 0;12    Node* p = head;13    // do … while: walk until back at head14    return n;15}16 17int main() {18    Node* last = new Node(4);19    Node* head = new Node(1, new Node(2, new Node(3, last)));20    last->next = head;21    cout << count(head) << "\n";22    last->next = nullptr;23    while (head != nullptr) {24        Node* next = head->next;25        delete head;26        head = next;27    }28    return 0;29}
Output
Press Run or Ctrl+Enter

With the STL

std::list is a circular doubly linked list plus one sentinel node (as g++ writes it): the sentinel holds no data, its next is the first element and its prev the last; end() points at that sentinel, so --end() is the last element. With the sentinel every real node has nodes on both sides, so the if (p->next != nullptr) in insert and delete is never needed.

Its two most useful features:

  • splice: unhook nodes from one place and hook them in elsewhere (in the same list or another one), changing only pointers: no copying, no new, no delete; one node or a whole list is O(1).
  • Iterators stay valid: inserting, erasing or splicing other elements leaves an iterator to an element valid (the node has not moved, only its neighbours' pointers changed). Only when that element itself is erased does its iterator die. vector is different: an insert may move the whole block, and every old iterator dies.
main.cpp
1#include <iostream>2#include <list>3using namespace std;4 5void show(const list<int>& lst) {6    for (int x : lst)7        cout << x << " ";8    cout << "\n";9}10 11int main() {12    list<int> a = {1, 2, 3};13    list<int> b = {7, 8, 9};14    auto it = a.begin();15    ++it;                              // it points at 216 17    for (auto r = a.rbegin(); r != a.rend(); ++r)18        cout << *r << " ";             // walk backward: along prev19    cout << "\n";20    cout << *(--a.end()) << "\n";      // end() is the sentinel; the one before it is the last21 22    a.splice(it, b);                   // all of b goes in before 2: O(1)23    show(a);24    cout << b.size() << " " << *it << "\n";   // b is empty; it still points at 225 26    a.splice(a.begin(), a, it);        // move just the node 2 to the front27    show(a);28    cout << *it << "\n";               // still 229    return 0;30}
Output
3 2 1 
3
1 7 8 9 2 3 
0 2
2 1 7 8 9 3 
2

Put unordered_map and list together and you have the LRU cache that interviews ask for again and again (holds at most cap items, throws out the least recently used when full; get and put must be O(1)): the list runs from most recently used to least, and the unordered_map keeps each key's iterator into the list. When a key is used, splice it to the front; when full, remove the list's last one. Because iterators stay valid, the positions stored in the map keep working.

main.cpp
1#include <iostream>2#include <list>3#include <unordered_map>4#include <utility>5using namespace std;6 7class LRUCache {8    int cap;9    list<pair<int, int>> items;                              // (key, val): most recent at the front10    unordered_map<int, list<pair<int, int>>::iterator> pos;  // key -> its position in items11public:12    LRUCache(int c) : cap(c) {}13 14    int get(int key) {15        auto f = pos.find(key);16        if (f == pos.end())17            return -1;18        items.splice(items.begin(), items, f->second);   // used: move to the front19        return f->second->second;20    }21 22    void put(int key, int val) {23        auto f = pos.find(key);24        if (f != pos.end()) {25            f->second->second = val;26            items.splice(items.begin(), items, f->second);27            return;28        }29        if ((int)items.size() == cap) {30            pos.erase(items.back().first);    // least recently used: the last one31            items.pop_back();32        }33        items.push_front(make_pair(key, val));34        pos[key] = items.begin();35    }36};37 38int main() {39    LRUCache c(2);40    c.put(1, 1);41    c.put(2, 2);42    cout << c.get(1) << " ";43    c.put(3, 3);           // full: 2 is least recently used, out it goes44    cout << c.get(2) << " ";45    c.put(4, 4);           // full: 1 is least recently used, out it goes46    cout << c.get(1) << " " << c.get(3) << " " << c.get(4) << "\n";47    return 0;48}
Output
1 -1 -1 3 4
std::list operationCostNote
push_front / push_back / pop_front / pop_backO(1)both ends are fast
insert(it, x) / erase(it)O(1)once you hold an iterator
splice one node or a whole listO(1)pointers only
--end(), rbegin() walking backO(1) per stepalong prev
Find a value, reach the i-thO(n)no index

In interviews: the standard answer to LRU cache (LeetCode 146) is the one above: a doubly linked list plus a hash table, get and put both O(1). The interviewer may ask you to drop std::list and write the doubly linked list by hand; then write this lesson's DNode, with a sentinel at each end so insert and delete never check for nullptr.

Guess the outputA wrong guess is fine

splice moves the 2 node to the end, then the whole list and *it are printed. What shows?

1#include <iostream>2#include <list>3using namespace std;4 5int main() {6    list<int> a = {1, 2, 3, 4};7    auto it = a.begin();8    ++it;9    a.splice(a.end(), a, it);10    for (int x : a)11        cout << x << " ";12    cout << *it << "\n";13    return 0;14}
Choose one

The LRUCache c(2) from this step does put(1, 1), put(2, 2), get(1), put(3, 3) in turn. Which key is thrown out by put(3, 3)?

Summary

Take-away

Doubly linked lists walk back; circular lists join end to start; std::list is both

  • Doubly linked insert, 4 steps: s->next, p->next->prev, s->prev, and last p->next
  • Doubly linked delete: skip it in both directions, then delete
  • Walking a circular list: stop when back at the start, with do … while
  • std::list: a circular doubly linked list with a sentinel; splice is O(1), iterators stay valid
1s->next = p->next;2p->next->prev = s;3s->prev = p;4p->next = s;5lst.splice(lst.begin(), lst, it);   // move to the front