Searching a sorted linked list is slow: you must walk node by node, so it takes O(n) time. A skip list fixes this by adding “express lanes”. Some nodes also appear in higher levels that skip over many nodes at once, like an express train that stops only at major stations. A search starts on the top level, moves forward as far as it can, then drops down a level. Which nodes get express stops is decided by coin flips, and on average search, insert and delete all take O(log n). Redis uses skip lists for its sorted sets.
In this lesson you will learn
- How the levels of a skip list are arranged
- Choosing a node’s height with random coin flips
- Searching from the top level down
- Inserting and deleting with an
updatearray - Range queries, and how skip lists compare with balanced trees
You should know linked lists, binary search and Big O notation.
Levels, Search and Insert
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_LEVEL 4
typedef struct Node {
int key;
struct Node *next[MAX_LEVEL]; /* next[i] = next node on level i */
} Node;
typedef struct { Node head; int level; } SkipList;
/* Tiny fixed random generator, so the output is the same every run */
static unsigned seed = 12345;
static unsigned rnd(void) { seed = seed * 1103515245u + 12345u; return (seed >> 16) & 0x7fff; }
/* Coin flips: level 1 always, each extra level with probability 1/2 */
int randomLevel(void) {
int lvl = 1;
while (lvl < MAX_LEVEL && (rnd() & 1)) lvl++;
return lvl;
}
void insert(SkipList *sl, int key) {
Node *update[MAX_LEVEL], *x = &sl->head;
for (int i = sl->level - 1; i >= 0; i--) { /* go down level by level */
while (x->next[i] && x->next[i]->key < key) x = x->next[i];
update[i] = x; /* last node before key on level i */
}
int lvl = randomLevel();
for (int i = sl->level; i < lvl; i++) update[i] = &sl->head;
if (lvl > sl->level) sl->level = lvl;
Node *n = calloc(1, sizeof *n);
if (!n) { perror("calloc"); exit(1); }
n->key = key;
for (int i = 0; i < lvl; i++) { /* splice in on each level */
n->next[i] = update[i]->next[i];
update[i]->next[i] = n;
}
}
int search(const SkipList *sl, int key, int *steps) {
const Node *x = &sl->head;
*steps = 0;
for (int i = sl->level - 1; i >= 0; i--)
while (x->next[i] && x->next[i]->key < key) { x = x->next[i]; (*steps)++; }
x = x->next[0];
return x && x->key == key;
}
void print(const SkipList *sl) {
for (int i = sl->level - 1; i >= 0; i--) {
printf("level %d: ", i);
for (const Node *x = sl->head.next[i]; x; x = x->next[i]) printf("%d ", x->key);
printf("\n");
}
}
void freeAll(SkipList *sl) {
Node *x = sl->head.next[0];
while (x) { Node *nx = x->next[0]; free(x); x = nx; }
}
int main(void) {
SkipList sl = { .head = { .key = INT_MIN }, .level = 1 };
int keys[] = { 30, 10, 70, 50, 20, 90, 60, 40, 80 };
for (int i = 0; i < 9; i++) insert(&sl, keys[i]);
print(&sl);
int targets[] = { 60, 35, 90 }, steps;
for (int i = 0; i < 3; i++) {
int found = search(&sl, targets[i], &steps);
printf("search %d: %s after %d forward step(s)\n",
targets[i], found ? "found" : "not found", steps);
}
freeAll(&sl);
return 0;
}
Output
level 3: 50
level 2: 50 80
level 1: 40 50 60 70 80
level 0: 10 20 30 40 50 60 70 80 90
search 60: found after 1 forward step(s)
search 35: not found after 3 forward step(s)
search 90: found after 2 forward step(s)
- Level 0 is an ordinary sorted linked list containing every key. Each higher level holds a subset of the keys below it.
next[i]is the node’s pointer on leveli. A node of height 3 hasnext[0],next[1]andnext[2].randomLevelflips a coin: every node gets level 0, and each extra level is added with probability 1/2. About half the nodes reach level 1, a quarter level 2, and so on.- Search starts at the head on the highest level. It moves right while the next key is smaller than the target, then drops down one level. Searching for 60 takes just one step on level 3 (to 50), then drops straight down.
- Insert runs the same search and records in
update[i]the last node before the new key on each level. The new node is then spliced in after those nodes, just like inserting into a linked list. - The program uses its own tiny random generator so the output is the same on every computer.
Delete, Range Queries and Performance
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_LEVEL 16
typedef struct Node { int key; struct Node *next[MAX_LEVEL]; } Node;
typedef struct { Node head; int level; } SkipList;
static unsigned seed = 2026;
static unsigned rnd(void) { seed = seed * 1103515245u + 12345u; return (seed >> 16) & 0x7fff; }
static int randomLevel(void) { int l = 1; while (l < MAX_LEVEL && (rnd() & 1)) l++; return l; }
void insert(SkipList *sl, int key) {
Node *update[MAX_LEVEL], *x = &sl->head;
for (int i = sl->level - 1; i >= 0; i--) {
while (x->next[i] && x->next[i]->key < key) x = x->next[i];
update[i] = x;
}
if (x->next[0] && x->next[0]->key == key) return; /* no duplicates */
int lvl = randomLevel();
for (int i = sl->level; i < lvl; i++) update[i] = &sl->head;
if (lvl > sl->level) sl->level = lvl;
Node *n = calloc(1, sizeof *n);
if (!n) { perror("calloc"); exit(1); }
n->key = key;
for (int i = 0; i < lvl; i++) { n->next[i] = update[i]->next[i]; update[i]->next[i] = n; }
}
/* Delete: find the node on every level and unlink it */
int erase(SkipList *sl, int key) {
Node *update[MAX_LEVEL], *x = &sl->head;
for (int i = sl->level - 1; i >= 0; i--) {
while (x->next[i] && x->next[i]->key < key) x = x->next[i];
update[i] = x;
}
x = x->next[0];
if (!x || x->key != key) return 0;
for (int i = 0; i < sl->level && update[i]->next[i] == x; i++)
update[i]->next[i] = x->next[i];
free(x);
while (sl->level > 1 && !sl->head.next[sl->level - 1]) sl->level--;
return 1;
}
long countSteps(const SkipList *sl, int key) {
const Node *x = &sl->head; long s = 0;
for (int i = sl->level - 1; i >= 0; i--)
while (x->next[i] && x->next[i]->key < key) { x = x->next[i]; s++; }
return s;
}
int main(void) {
SkipList sl = { .head = { .key = INT_MIN }, .level = 1 };
const int N = 100000;
for (int k = 1; k <= N; k++) insert(&sl, k * 2); /* even numbers 2..200000 */
printf("levels used: %d\n", sl.level);
long total = 0;
for (int k = 1; k <= 1000; k++) total += countSteps(&sl, k * 199);
printf("average forward steps per search: %.1f (a plain list needs ~%d)\n",
total / 1000.0, N / 2);
printf("erase 500: %s, erase 501: %s\n",
erase(&sl, 500) ? "removed" : "missing", erase(&sl, 501) ? "removed" : "missing");
/* Range query: walk level 0 from the first key >= 990 */
const Node *x = &sl.head;
for (int i = sl.level - 1; i >= 0; i--)
while (x->next[i] && x->next[i]->key < 990) x = x->next[i];
printf("keys in [990, 1010]: ");
for (x = x->next[0]; x && x->key <= 1010; x = x->next[0]) printf("%d ", x->key);
printf("\n");
Node *p = sl.head.next[0];
while (p) { Node *nx = p->next[0]; free(p); p = nx; }
return 0;
}
Output
levels used: 16
average forward steps per search: 17.3 (a plain list needs ~50000)
erase 500: removed, erase 501: missing
keys in [990, 1010]: 990 992 994 996 998 1000 1002 1004 1006 1008 1010
- With 100,000 keys, a search needs about 17 forward steps on average. A plain sorted linked list would need about 50,000.
- Delete finds the
updatenodes the same way, then unlinks the node on every level it appears in. Empty top levels are removed afterwards. - Range queries are easy: find the first key at or after the start, then walk along level 0. This is one reason databases like skip lists.
- Duplicate keys are rejected by checking the node right after the search position.
| Operation | Sorted linked list | Skip list (average) | Balanced BST |
|---|---|---|---|
| Search | O(n) | O(log n) | O(log n) |
| Insert / delete | O(n) | O(log n) | O(log n) |
| Ordered walk | Easy | Easy (level 0) | In-order traversal |
| Code difficulty | Easy | Moderate | Hard (rotations) |
Common Mistakes
- Forgetting to set
update[i]to the head for new levels above the current height, so the new node is not linked on those levels. - Calling
rand()without understanding it, or seeding it inside the insert function, which can give the same level every time. - Freeing nodes by walking a higher level instead of level 0, which misses most nodes.
- Expecting a guaranteed O(log n). The bound is on average; an unlucky run of coin flips can be slower.
Practice Exercises
Exercise 1. On average, how many nodes reach level 3 or higher in a skip list with 1,000 keys, using p = 1/2?
Show answer
A node reaches level 3 only if three coin flips in a row come up heads: (1/2)3 = 1/8. So about 1000 / 8 = 125 nodes.
Exercise 2. Write a function int countKeys(const SkipList *sl).
Show answer
int countKeys(const SkipList *sl) {
int n = 0;
for (const Node *x = sl->head.next[0]; x; x = x->next[0]) n++;
return n;
}
Every key appears on level 0, so counting that level is enough.
Frequently Asked Questions
Why use a skip list instead of a balanced tree?
Skip lists are easier to write correctly, because they need no rotations. They also handle range walks naturally and are easier to make safe for many threads at once. Balanced trees give a worst-case guarantee, which skip lists do not.
How tall should a skip list be?
About log2(n) levels is enough with p = 1/2. For one million keys that is around 20 levels, so a fixed maximum of 16 to 32 levels covers most programs.
Summary
- A skip list is a sorted linked list with extra “express” levels.
- Coin flips decide each node’s height, giving O(log n) average search, insert and delete.
- Insert and delete use an
updatearray of the last node before the key on each level. - Range queries are simple walks along level 0.
Next: Manacher’s Algorithm in C.
