Kodewick
Start learning →
Inserting and deleting in a linked list10 / 52

Inserting and deleting in a linked list

Lesson 10 of 52 · Part 2 · Arrays and linked lists · about 16 minutes

Inserting into a linked list changes two pointers, the one after first: d->next = p->next, then p->next = d; deleting saves the node, skips it and calls delete, and std::list has insert and erase.

To put a number into the middle of a row, a vector moves every element after it one place along; a linked list changes two pointers. In this lesson you change those two pointers in C++, delete the nodes you remove, see what to do at the very front, and look at std::list's insert and erase.

Above, an array: inserting 5 at index 1 moves the 4 numbers after it one cell each. Below, a linked list: the same insert of 5 changes only two arrows

The node is the same as last lesson:

1struct Node {2    int val;3    Node* next;     // the next node's address; nullptr in the last one4    Node(int v, Node* n = nullptr) : val(v), next(n) {}5};

How many items an array insert moves

An array’s or a vector’s items sit side by side in memory. To put 5 at index 1, you first have to make room: starting from the last one, every item moves one place back. That is what vector’s insert does inside too.

Guess the outputA wrong guess is fine

Inserting 5 at index 1: what does this code print?

1#include <iostream>2using namespace std;3 4int main() {5    int a[6] = {3, 7, 9, 11, 13};6    int n = 5, moves = 0;7    for (int i = n; i > 1; i--) {8        a[i] = a[i - 1];9        moves++;10    }11    a[1] = 5;12    cout << moves << "\n";13    return 0;14}
Choose one

In a sequential list (an array or vector) of length n, inserting a number at the very front (index 0) moves how many items?

Inserting in the middle: two steps, in this order

An array's elements sit side by side, so inserting at index 1 moves every element after index 1 one cell along. A linked list's nodes come one by one from new, scattered on the heap and linked by next, so inserting moves nothing: only next changes.

The list is 3 → 7 → 9, pointer p points at node 3, and 5 goes in after it.

p↓
3a
5d
7b
9c
nullptr

Inserting 5 between 3 and 7: link what comes after, then change what comes before
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 10void show(Node* head) {11    for (Node* q = head; q != nullptr; q = q->next)12        cout << q->val << " -> ";13    cout << "nullptr\n";14}15 16void clear(Node* head) {17    while (head != nullptr) {18        Node* next = head->next;19        delete head;20        head = next;21    }22}23 24int main() {25    Node* head = new Node(3, new Node(7, new Node(9)));26    show(head);27 28    Node* p = head;29    // 1. the new node30    Node* d = new Node(5);31    // 2. link what comes after32    d->next = p->next;33    // 3. then change what comes before34    p->next = d;35    show(head);36    clear(head);37    return 0;38}
Output
3 -> 7 -> 9 -> nullptr
3 -> 5 -> 7 -> 9 -> nullptr

Press Step to see d appear on the heap, then watch the addresses in d->next and p->next change. (The folded show prints the whole list and clear deletes the nodes one by one, as last lesson.) With the constructor, the first three steps can be one line: p->next = new Node(5, p->next);, where the right side is worked out first, still using the old p->next.

Put in orderDrag, or use the arrows

Put these three lines in order: d points at the new node 5, which goes after p (node 3), so the program prints 3 5 7 9.

  1. p->next = d;
  2. Node* d = &e;
  3. d->next = p->next;
Should print
3 5 7 9

What if the order is reversed

What if you write p->next = d; first, and then d->next = p->next;?

Guess the outputA wrong guess is fine

With the order reversed, 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), d(5);12    Node* p = &a;13    p->next = &d;14    d.next = p->next;15    cout << d.next->val << " " << (d.next == &d) << "\n";16    return 0;17}

Remember: link what comes after, then change what comes before. Change the front first and the rest of the list's address is gone.

Deleting: save it, skip it, delete it

To delete the 7 after 3, make 3 point straight at 9. But node 7 came from new; after skipping it you still have to delete it, or that memory leaks. So first keep hold of it with a pointer gone.

p↓
3a
7b
9c
nullptr

Deleting 7: keep hold of it, make 3 skip it, then give its memory back

After delete, gone still holds the same address, but that memory is no longer yours. A pointer like that is called "dangling": using it again is a bug.

Stack

pNode*
goneNode*nullptr

Heap

3Node
7Node
9Node

After delete, gone still holds the old address: it dangles; setting it to nullptr is safest
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 10void show(Node* head) {11    for (Node* q = head; q != nullptr; q = q->next)12        cout << q->val << " -> ";13    cout << "nullptr\n";14}15 16void clear(Node* head) {17    while (head != nullptr) {18        Node* next = head->next;19        delete head;20        head = next;21    }22}23 24int main() {25    Node* head = new Node(3, new Node(7, new Node(9)));26    Node* p = head;27    // 1. keep hold of 728    Node* gone = p->next;29    // 2. skip it30    p->next = gone->next;31    // 3. give it back32    delete gone;33    gone = nullptr;34    show(head);35    clear(head);36    return 0;37}
Output
3 -> 9 -> nullptr

Swap steps 2 and 3, delete gone first and then read gone->next, and you read memory that has been given back. That is "undefined behaviour": it may look fine, or read garbage, or crash, and you cannot count on any of them. delete nullptr does nothing, so once it is set to nullptr, one delete too many does no harm.

Fill inTap one to fill a blank; tap a blank to take it back

Delete node 7 after p: fill the blank so the program prints 3 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* head = new Node(3, new Node(7, new Node(9)));12    Node* p = head;13    Node* gone = p->next;14    p->next = ;15    delete gone;16    cout << p->val << " " << p->next->val << "\n";17    delete p->next;18    delete p;19    return 0;20}
Choose one

After delete gone;, what does gone hold?

Exercise 1

Delete the one after 2

The list is 1 -> 2 -> 9 -> 3, and 9 got in by mistake. Complete delete_after: remove the node after p and delete it.

It should print
1 -> 2 -> 3 -> nullptr
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 10void show(Node* head) {11    for (Node* q = head; q != nullptr; q = q->next)12        cout << q->val << " -> ";13    cout << "nullptr\n";14}15 16void clear(Node* head) {17    while (head != nullptr) {18        Node* next = head->next;19        delete head;20        head = next;21    }22}23 24void delete_after(Node* p) {25    // save it, skip it, delete it26}27 28int main() {29    Node* head = new Node(1, new Node(2, new Node(9, new Node(3))));30    delete_after(head->next);31    show(head);32    clear(head);33    return 0;34}
Output
Press Run or Ctrl+Enter

The first node has no node before it, so you change head itself: the new node points at the old first one, then head points at the new node, that is head = new Node(v, head);.

In a function there is a trap: void push_front(Node* head, int v) gets a copy of head, changes only the copy, and main's head stays the same. In C you would pass Node**; in C++ pass a reference Node*& head, and the head in the function is main's variable itself:

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 10void show(Node* head) {11    for (Node* q = head; q != nullptr; q = q->next)12        cout << q->val << " -> ";13    cout << "nullptr\n";14}15 16void clear(Node* head) {17    while (head != nullptr) {18        Node* next = head->next;19        delete head;20        head = next;21    }22}23 24void push_front_copy(Node* head, int v) {25    head = new Node(v, head);    // changes only the copy: nobody keeps the new node, it leaks26}27 28void push_front(Node*& head, int v) {29    head = new Node(v, head);    // changes main's head itself30}31 32int main() {33    Node* head = new Node(3, new Node(7));34    push_front_copy(head, 0);35    show(head);36    push_front(head, 1);37    show(head);38    clear(head);39    return 0;40}
Output
3 -> 7 -> nullptr
1 -> 3 -> 7 -> nullptr
Guess the outputA wrong guess is fine

push_front is meant to put 1 at the front. What does main 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 10void push_front(Node* head, int v) {11    head = new Node(v, head);12}13 14int main() {15    Node b(7), a(3, &b);16    Node* head = &a;17    push_front(head, 1);18    cout << head->val << "\n";19    return 0;20}

A dummy node: the front is no longer special

Inserting at the front means changing head, and in a function you also have to remember the reference: easy to miss. The textbook way out is the "list with a head node", called a dummy node in LeetCode solutions: put a node that holds no data at the front, L, and the real first element is L->next.

L↓
dummyh
1d
3a
7b
nullptr

With a dummy node: inserting at the front is written the same as inserting in the middle

With a dummy node, inserting at the front is "inserting after the dummy node", exactly like inserting in the middle; L never changes and the function never has to change head. Deleting the first node is the same: the node before it is L. The textbook's LinkList L is a pointer to that head node.

Choose one

A singly linked list L with a dummy node: how do you test that it is empty?

Exercise 2

With a dummy node, insert at position i

L is the dummy node and the list is 10 -> 30. Complete list_insert: put e at position i (counting from 1) by walking to node i−1 first. Make the program print 5 -> 10 -> 20 -> 30 -> nullptr.

It should print
5 -> 10 -> 20 -> 30 -> nullptr
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 10void show(Node* head) {11    for (Node* q = head; q != nullptr; q = q->next)12        cout << q->val << " -> ";13    cout << "nullptr\n";14}15 16void clear(Node* head) {17    while (head != nullptr) {18        Node* next = head->next;19        delete head;20        head = next;21    }22}23 24void list_insert(Node* L, int i, int e) {25    Node* p = L;   // start from the dummy node26    // walk i-1 steps, then insert e after p27}28 29int main() {30    Node* L = new Node(0, new Node(10, new Node(30)));31    list_insert(L, 2, 20);32    list_insert(L, 1, 5);33    show(L->next);34    clear(L);35    return 0;36}
Output
Press Run or Ctrl+Enter

What is fast, what is slow

OperationArray / vectorLinked list
Get the i-thO(1): a[i] works out the address from the indexO(n): walk from the head one by one
Insert or delete after a pointer p you already haveO(n): everything after movesO(1): change one or two pointers
Insert at position i (find it first)O(n)O(n): the finding walks

A common trap in interviews and exams: "linked list insert and delete are O(1)" holds only once you have a pointer to the node before; inserting at a position means walking to node i−1 first, which is still O(n).

Choose one

In a singly linked list you already have a pointer to node p and insert after it; compared with “insert at position i”, what are the two time complexities?

With the STL

std::list inserts and deletes through iterators (a "position" pointing at an element, the hand-written p):

  • lst.insert(it, x): puts x before it and returns an iterator to the new element. it still points at the element it pointed at.
  • lst.erase(it): removes the element it points at (deleting that node inside) and returns an iterator to the next one. The erased it dangles and must not be used.
  • push_front / push_back / pop_front / pop_back: add and remove at either end.
  • lst.remove(x): removes every element equal to x, walking the whole list.
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 << "end\n";9}10 11int main() {12    list<int> lst = {3, 7, 9};13    auto it = lst.begin();14    ++it;                        // it points at 715    lst.insert(it, 5);           // goes before 7; it still points at 716    show(lst);17 18    it = lst.erase(it);          // remove 7, get the next one back19    cout << *it << "\n";20    show(lst);21 22    lst.push_front(1);23    lst.push_back(10);24    show(lst);25 26    // erase while walking: remove every even number27    for (auto q = lst.begin(); q != lst.end(); ) {28        if (*q % 2 == 0)29            q = lst.erase(q);    // carry on from erase's return value30        else31            ++q;32    }33    show(lst);34 35    lst.remove(5);36    show(lst);37    return 0;38}
Output
3 -> 5 -> 7 -> 9 -> end
9
3 -> 5 -> 9 -> end
1 -> 3 -> 5 -> 9 -> 10 -> end
1 -> 3 -> 5 -> 9 -> end
1 -> 3 -> 9 -> end

Erasing while you walk must be q = lst.erase(q): with lst.erase(q); ++q;, q already dangles, and ++q reads next from a deleted node, the same bug as reading next after delete in the hand-written list.

Operationlistvector
insert(it, x) / erase(it)O(1)O(n): everything after moves
push_front / pop_frontO(1)not there; insert(begin(), x) is O(n)
push_back / pop_backO(1)amortised O(1)
Finding the positionO(n)O(1) (by index), or O(n) (by value)
remove(x)O(n)no member; erase(remove(…), end()), O(n)

In interviews: asked "list insert is O(1), so why is vector used more in practice?", answer: the O(1) assumes you already hold an iterator; finding the position is O(n), and the nodes are scattered on the heap, each allocated on its own, so walking is much slower than contiguous memory. In hand-written list problems, deleting the first node and inserting at the front are easy to get wrong: start with a dummy node.

Guess the outputA wrong guess is fine

erase first, then insert at the iterator it returns. What is printed?

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

Summary

Take-away

Insert: link what comes after, then what comes before; delete: save, skip, delete

  • With a pointer to the node before, insert and delete are O(1); finding by position is still O(n)
  • After delete the pointer dangles: set it to nullptr
  • Inserting at the front changes head: pass Node*&, or use a dummy node
  • std::list: insert goes before it, erase returns the next one
1d->next = p->next;     // insert2p->next = d;3Node* gone = p->next;  // delete4p->next = gone->next;5delete gone;