Kodewick
Start learning →
Inserting and deleting in a linked list8 / 50

Inserting and deleting in a linked list

Lesson 8 of 50 · Part 2 · Arrays and linked lists · about 15 minutes

Inserting into a linked list takes two steps in a fixed order, d->next = p->next; then p->next = d;, and deleting means keeping the node, skipping it and calling free; with a dummy head node, the front needs no special case.

To put a number in the middle of a row, an array moves every number after it; a linked list changes two pointers. In this lesson you change those two pointers in C, free the node you delete, and see why textbooks like a dummy head node.

Top, an array: putting 5 at index 1 moves the 4 numbers after it one place right. Bottom, a linked list: the same 5 goes in by changing two arrows

How many elements an array moves

An array keeps its elements side by side in memory. To put 5 at index 1 you first make room: starting from the last one, every element moves one place right.

Guess the outputA wrong guess is fine

This inserts 5 at index 1. What does it print?

1#include <stdio.h>2 3int main(void) {4    int a[6] = {3, 7, 9, 11, 13};5    int n = 5, moves = 0;6    for (int i = n; i > 1; i--) {7        a[i] = a[i - 1];8        moves++;9    }10    a[1] = 5;11    printf("%d\n", moves);12    return 0;13}

A linked list's nodes are malloced one at a time and sit anywhere on the heap. Each node keeps the next node's address in next, so inserting moves nothing: only next changes.

This lesson's node:

1typedef struct Node {2    int data;3    struct Node *next;   // the next node's address; NULL in the last one4} Node;
Choose one

An array list holds n elements. To insert a number at the very front (index 0), how many elements have to move?

Inserting in the middle: two steps, in this order

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

p↓
3a
5d
7b
9c
NULL

Inserting 5 between 3 and 7: link what comes after, then change what comes before
main.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16void show(Node *head) {17    for (Node *q = head; q != NULL; q = q->next)18        printf("%d -> ", q->data);19    printf("NULL\n");20}21 22int main(void) {23    Node *head = new_node(3, new_node(7, new_node(9, NULL)));24    show(head);25 26    Node *p = head;27    // 1. a new node28    Node *d = new_node(5, NULL);29    // 2. link what comes after30    d->next = p->next;31    // 3. then change what comes before32    p->next = d;33    show(head);34    return 0;35}
Output
3 -> 7 -> 9 -> NULL
3 -> 5 -> 7 -> 9 -> NULL

Press Step to see d appear on the heap, then watch the addresses in d->next and p->next change.

Put in orderDrag, or use the arrows

Put these three lines in order: d points at the new node 5, which goes in 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
Exercise 1

Insert 3 after 2

The list is 1 -> 2 -> 4. Finish insert_after so it inserts data after p.

It should print
1 -> 2 -> 3 -> 4 -> NULL
exercise1.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16void show(Node *head) {17    for (Node *q = head; q != NULL; q = q->next)18        printf("%d -> ", q->data);19    printf("NULL\n");20}21 22void insert_after(Node *p, int data) {23    Node *d = new_node(data, NULL);24    // link what comes after, then what comes before25}26 27int main(void) {28    Node *head = new_node(1, new_node(2, new_node(4, NULL)));29    insert_after(head->next, 3);30    show(head);31    return 0;32}
Output
Press Run or Ctrl+Enter

What if the order is reversed

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

Guess the outputA wrong guess is fine

With the order reversed, what does this print?

1#include <stdio.h>2 3typedef struct Node {4    int data;5    struct Node *next;6} Node;7 8int main(void) {9    Node c = {9, NULL}, b = {7, &c}, a = {3, &b}, d = {5, NULL};10    Node *p = &a;11    p->next = &d;12    d.next = p->next;13    printf("%d %d\n", d.next->data, d.next == &d);14    return 0;15}

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: keep it, skip it, free it

To delete the 7 after 3, point 3 straight at 9. But in C node 7 came from malloc: once it is skipped it must be freed, or the memory leaks. So first keep it in a pointer, gone.

p↓
3a
7b
9c
NULL

Deleting 7: keep it, let 3 skip it, then give its memory back

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

stack

pNode *
goneNode *NULL

heap

3Node
7Node
9Node

After free, gone still holds the old address: it dangles, so set it to NULL
main.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16void show(Node *head) {17    for (Node *q = head; q != NULL; q = q->next)18        printf("%d -> ", q->data);19    printf("NULL\n");20}21 22int main(void) {23    Node *head = new_node(3, new_node(7, new_node(9, NULL)));24    Node *p = head;25    // 1. keep the 7 to delete26    Node *gone = p->next;27    // 2. skip it28    p->next = gone->next;29    // 3. give it back30    free(gone);31    gone = NULL;32    show(head);33    return 0;34}
Output
3 -> 9 -> NULL

Try swapping steps 2 and 3: free(gone) first, then read gone->next, which is memory you already gave back. Press Run and see what happens.

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

Delete node 7, the one after p: fill in the blank so the program prints 3 9.

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9int main(void) {10    Node *c = malloc(sizeof(Node)), *b = malloc(sizeof(Node)), *a = malloc(sizeof(Node));11    c->data = 9; c->next = NULL;12    b->data = 7; b->next = c;13    a->data = 3; a->next = b;14    Node *p = a;15    Node *gone = p->next;16    p->next = ;17    free(gone);18    printf("%d %d\n", p->data, p->next->data);19    return 0;20}
Choose one

After free(gone); runs, what is stored in gone?

Exercise 2

Delete the node after 2

The list is 1 -> 2 -> 9 -> 3, and 9 doesn't belong. Finish delete_after: delete the node after p and free it.

It should print
1 -> 2 -> 3 -> NULL
exercise2.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16void show(Node *head) {17    for (Node *q = head; q != NULL; q = q->next)18        printf("%d -> ", q->data);19    printf("NULL\n");20}21 22void delete_after(Node *p) {23    // keep it, skip it, then free it24}25 26int main(void) {27    Node *head = new_node(1, new_node(2, new_node(9, new_node(3, NULL))));28    delete_after(head->next);29    show(head);30    return 0;31}
Output
Press Run or Ctrl+Enter

Nothing comes before the first node, so head itself changes: the new node points at the old first node, then head points at the new node.

head↓
1d
3a
7b
NULL

Inserting 1 at the front: the new node points at the old first node, then head moves to it

There is a trap in C: head is a variable in main. A function push_front(head, 1) changes only its own copy of head; the one in main stays. Two usual ways out: the function returns the new head (head = push_front(head, 1);), or it takes the address of head (Node **).

Guess the outputA wrong guess is fine

push_front is meant to put 1 at the front. What does main print?

1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9void push_front(Node *head, int data) {10    Node *d = malloc(sizeof(Node));11    d->data = data;12    d->next = head;13    head = d;14}15 16int main(void) {17    Node b = {7, NULL}, a = {3, &b};18    Node *head = &a;19    push_front(head, 1);20    printf("%d\n", head->data);21    return 0;22}

A dummy head node: the front stops being special

Textbooks often give a singly linked list a dummy head node: a node L at the front that holds no data, with the real first element at L->next.

L↓
headh
1d
3a
7b
NULL

With a dummy head, inserting at the front is written like inserting in the middle

With a dummy head, inserting at the front is inserting after the dummy, exactly like the middle; L never changes, and no function has to return a new head. A textbook's LinkList L is a pointer to that dummy node.

Choose one

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

Exercise 3

With a dummy head, insert at position i

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

It should print
5 -> 10 -> 20 -> 30 -> NULL
exercise3.c
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5    int data;6    struct Node *next;7} Node;8 9Node *new_node(int data, Node *next) {10    Node *n = malloc(sizeof(Node));11    n->data = data;12    n->next = next;13    return n;14}15 16void show(Node *L) {17    for (Node *q = L->next; q != NULL; q = q->next)18        printf("%d -> ", q->data);19    printf("NULL\n");20}21 22void list_insert(Node *L, int i, int e) {23    Node *p = L;   // start at the dummy head24    // take i-1 steps, then insert e after p25}26 27int main(void) {28    Node *L = new_node(0, new_node(10, new_node(30, NULL)));29    list_insert(L, 2, 20);30    list_insert(L, 1, 5);31    show(L);32    return 0;33}
Output
Press Run or Ctrl+Enter

What is fast and what is slow

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

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 hold a pointer to node p and insert after it. Compared with "insert at position i", what are the two time complexities?

Summary

Take-away

Insert: link what comes after, then before. Delete: keep it, skip it, free it

  • With a pointer to the node before, insert and delete are O(1); finding a position is still O(n)
  • After free the pointer dangles: set it to NULL
  • Inserting at the front changes head: return the new head, or use a dummy head
1d->next = p->next;     // insert2p->next = d;3Node *gone = p->next;  // delete4p->next = gone->next;5free(gone);