0Pricing
C Academy · Lesson

Insertion and Deletion

Modify the list.

Modifying a list

The strength of linked lists is cheap insertion and deletion. You rearrange pointers instead of shifting elements like in an array.

This lesson covers inserting and removing nodes at various positions.

#include <stdio.h>
#include <stdlib.h>

struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}

int main(void) {
    struct Node *head = make(2);
    printf("start: %d\n", head->value);
    free(head);
    return 0;
}

Insert at the front

Inserting at the head is O(1). Make a new node, point its next at the current head, then update the head to the new node.

#include <stdio.h>
#include <stdlib.h>

struct Node { int value; struct Node *next; };
struct Node *make(int v){struct Node*n=malloc(sizeof*n);n->value=v;n->next=NULL;return n;}

int main(void) {
    struct Node *head = make(2);
    struct Node *fresh = make(1);
    fresh->next = head;
    head = fresh;
    printf("%d -> %d\n", head->value, head->next->value);
    return 0;
}

All lessons in this course

  1. Singly Linked Lists
  2. Insertion and Deletion
  3. Traversal and Search
  4. Doubly Linked Lists
← Back to C Academy