Skip lists are a data structure that can be used in place of balanced trees. Skip lists use probabilistic balancing rather than strictly enforced balancing and as a result the algorithms for insertion and deletion in skip lists are much simpler and significantly faster than equivalent algorithms for balanced trees. –William Pugh
装在整理至:
跳表是由William Pugh发明的,上面的引言就是他给出的解释。跳表是一种随机化的数据结构,目前开源软件 Redis 和 LevelDB 都有用到它,它的效率和红黑树以及 AVL 树不相上下,但跳表的原理相当简单,只要你能熟练操作链表,就能轻松实现一个 SkipList。
跳跃表结构体 1 2 3 4 5 6 7 8 9 10 11 typedef struct node //每个节点的数据结构{ keyType key; valueType value; struct node *next [1]; } Node; typedef struct skip_list //跳表结构{ int level; Node *head; } skip_list;
柔性数组 sizeof(Node*)))柔性数组既数组大小待定的数组, C语言中结构体的最后一个元素可以是大小未知的数组,也就是所谓的0长度,所以我们可以用结构体来创建柔性数组。柔性数组既数组大小待定的数组, C语言中结构体的最后一个元素可以是大小未知的数组,也就是所谓的0长度,所以我们可以用结构体来创建柔性数组。
1 #define new_node(n) ((Node*)malloc(sizeof(Node)+n
跳跃表的插入 跳表的插入总结起来需要三步:
查找到待插入位置, 每层跟新update数组;
需要随机产生一个层数;
从高层至下插入,与普通链表的插入完全相同;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 int randomLevel () { int level=1 ; while (rand()%2 ) level++; level=(MAX_L>level)? level:MAX_L; return level; } bool insert (skip_list *sl, keyType key, valueType val) { Node *update[MAX_L]; Node *q=NULL ,*p=sl->head; int i=sl->level-1 ; for ( ; i>=0 ; --i) { while ((q=p->next[i])&& q->key<key) p=q; update[i]=p; } if (q && q->key == key) { q->value = val; return true ; } int level = randomLevel(); if (level>sl->level) { for (i=sl->level; i<level; ++i) { update[i]=sl->head; } sl->level=level; } q=create_node(level, key, val); if (!q) return false ; for (i=level-1 ; i>=0 ; --i) { q->next[i]=update[i]->next[i]; update[i]->next[i]=q; } return true ; }
删除节点 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 bool erase (skip_list *sl, keyType key) { Node *update[MAX_L]; Node *q=NULL , *p=sl->head; int i = sl->level-1 ; for (; i>=0 ; --i) { while ((q=p->next[i]) && q->key < key) { p=q; } update[i]=p; } if (!q || (q&&q->key != key)) return false ; for (i=sl->level-1 ; i>=0 ; --i) { if (update[i]->next[i]==q) { update[i]->next[i]=q->next[i]; if (sl->head->next[i]==NULL ) sl->level--; } } free (q); q=NULL ; return true ; }
查找操作 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 valueType *search (skip_list *sl, keyType key) { Node *q,*p=sl->head; q=NULL ; int i=sl->level-1 ; for (; i>=0 ; --i) { while ((q=p->next[i]) && q->key<key) { p=q; } if (q && key==q->key) return &(q->value); } return NULL ; }