跳跃表skiplist

本文将总结一种数据结构:跳跃表。前半部分跳跃表性质和操作的介绍直接摘自《让算法的效率跳起来--浅谈“跳跃表”的相关操作及其应用》上海市华东师范大学第二附属中学 魏冉。之后将附上跳跃表的源代码,以及本人对其的了解。难免有错误之处,希望指正,共同进步。谢谢。

    跳跃表(Skip List)是1987年才诞生的一种崭新的数据结构,它在进行查找、插入、删除等操作时的期望时间复杂度均为O(logn),有着近乎替代平衡树的本领。而且最重要的一点,就是它的编程复杂度较同类的AVL树,红黑树等要低得多,这使得其无论是在理解还是在推广性上,都有着十分明显的优势。

    首先,我们来看一下跳跃表的结构

   跳跃表由多条链构成(S0,S1,S2 ……,Sh),且满足如下三个条件:

  • 每条链必须包含两个特殊元素:+∞ 和 -∞(其实不需要)
  • S0包含所有的元素,并且所有链中的元素按照升序排列。
  • 每条链中的元素集合必须包含于序数较小的链的元素集合。

   操作

   一、查找
   目的:在跳跃表中查找一个元素x
   在跳跃表中查找一个元素x,按照如下几个步骤进行:
      1. 从最上层的链(Sh)的开头开始
      2. 假设当前位置为p,它向右指向的节点为q(p与q不一定相邻),且q的值为y。将y与x作比较
          (1) x=y  输出查询成功及相关信息
          (2) x>y  从p向右移动到q的位置
          (3) x<y  从p向下移动一格

      3. 如果当前位置在最底层的链中(S0),且还要往下移动的话,则输出查询失败

    二、插入
     目的:向跳跃表中插入一个元素x
     首先明确,向跳跃表中插入一个元素,相当于在表中插入一列从S0中某一位置出发向上的连续一段元素。有两个参数需要确定,即插入列的位置以及它的“高度”。
     关于插入的位置,我们先利用跳跃表的查找功能,找到比x小的最大的数y。根据跳跃表中所有链均是递增序列的原则,x必然就插在y的后面。
     而插入列的“高度”较前者来说显得更加重要,也更加难以确定。由于它的不确定性,使得不同的决策可能会导致截然不同的算法效率。为了使插入数据之后,保持该数据结构进行各种操作均为O(logn)复杂度的性质,我们引入随机化算法(Randomized Algorithms)。

     我们定义一个随机决策模块,它的大致内容如下:

  •  产生一个0到1的随机数r     r ← random()
  • 如果r小于一个常数p,则执行方案A,  if  r<p then do A
  • 否则,执行方案B         else do B

     初始时列高为1。插入元素时,不停地执行随机决策模块。如果要求执行的是A操作,则将列的高度加1,并且继续反复执行随机决策模块。直到第i次,模块要求执行的是B操作,我们结束决策,并向跳跃表中插入一个高度为i的列。


     我们来看一个例子:
     假设当前我们要插入元素“40”,且在执行了随机决策模块后得到高度为4
     步骤一:找到表中比40小的最大的数,确定插入位置

     步骤二:插入高度为4的列,并维护跳跃表的结构

    三、删除

    目的:从跳跃表中删除一个元素x
    删除操作分为以下三个步骤:

  • 在跳跃表中查找到这个元素的位置,如果未找到,则退出
  • 将该元素所在整列从表中删除
  • 将多余的“空链”删除 

    我们来看一下跳跃表的相关复杂度:
 
       空间复杂度: O(n)       (期望)
       跳跃表高度: O(logn)  (期望)


    相关操作的时间复杂度:
      查找:  O(logn)    (期望)
      插入:  O(logn)    (期望)
      删除:  O(logn)   (期望)
  
    之所以在每一项后面都加一个“期望”,是因为跳跃表的复杂度分析是基于概率论的。有可能会产生最坏情况,不过这种概率极其微小。

 


 

    以下是自己学习时碰到的一些问题

    首先分配一个链表,用list.hdr指向,长度为跳跃表规定的最高层,说是链表,在以下代码中只是分配了一段连续的空间,用来指向每一层的开始位置。我们看到结构体nodeType中,有一个key,一个rec(用户数据),还有一个指向结构体的指针数组。

 

    一开始的那些图容易给人误解。如上图所示,例如每个节点的forward[2],就认为是跳跃表的第3层。List.hdrforward[2]指向1111forward[2]指向3030forward[2]指向53。这就是跳跃表的第3层:11---30-----53。(准确的说每个forward都指向新节点,新节点的同层forward又指向另一个节点,从而构成一个链表,而数据只有一个,并不是像开始途中所画的那样有N个副本)。本人天资愚钝,看了挺长时间才把它在内存里的结构看清楚了,呵呵。  

 

 

    以下是在网上搜到的一个实现代码

 

    代码中主要注释了insert函数,剩下的两个函数差不多,就不一一注释了

  1 /* skip list */
  2 
  3 #include <stdio.h>
  4 #include <stdlib.h>
  5 
  6 /* implementation dependent declarations */
  7 typedef enum {
  8     STATUS_OK,
  9     STATUS_MEM_EXHAUSTED,
 10     STATUS_DUPLICATE_KEY,
 11     STATUS_KEY_NOT_FOUND
 12 } statusEnum;
 13 
 14 typedef int keyType;            /* type of key */
 15 
 16 /* user data stored in tree */
 17 typedef struct {
 18     int stuff;                  /* optional related data */
 19 } recType;
 20 
 21 #define compLT(a,b) (a < b)
 22 #define compEQ(a,b) (a == b)
 23 
 24 /* levels range from (0 .. MAXLEVEL) */
 25 #define MAXLEVEL 15
 26 
 27 typedef struct nodeTag {
 28     keyType key;                /* key used for searching */
 29     recType rec;                /* user data */
 30     struct nodeTag *forward[1]; /* skip list forward pointer */
 31 } nodeType;
 32 
 33 /* implementation independent declarations */
 34 typedef struct {
 35     nodeType *hdr;              /* list Header */
 36     int listLevel;              /* current level of list */
 37 } SkipList;
 38 
 39 SkipList list;                  /* skip list information */
 40 
 41 #define NIL list.hdr
 42 static int count = 0;
 43 statusEnum insert(keyType key, recType *rec) {
 44     int i, newLevel;
 45     nodeType *update[MAXLEVEL+1];
 46     nodeType *x;
 47     count++;
 48    /***********************************************
 49     *  allocate node for data and insert in list  *
 50     ***********************************************/
 51 
 52     /* find where key belongs */
 53     /*从高层一直向下寻找,直到这层指针为NIL,也就是说
 54     后面没有数据了,到头了,并且这个值不再小于要插入的值。
 55     记录这个位置,留着向其后面插入数据*/
 56     x = list.hdr;
 57     for (i = list.listLevel; i >= 0; i--) {
 58         while (x->forward[i] != NIL 
 59           && compLT(x->forward[i]->key, key))
 60             x = x->forward[i];
 61         update[i] = x;
 62     }
 63 
 64     
 65     /*现在让X指向第0层的X的后一个节点*/
 66     x = x->forward[0];
 67 
 68     
 69     /*如果相等就不用插入了*/
 70     if (x != NIL && compEQ(x->key, key)) 
 71         return STATUS_DUPLICATE_KEY;
 72 
 73    /*随机的计算要插入的值的最高level*/
 74     for (
 75       newLevel = 0; 
 76       rand() < RAND_MAX/2 && newLevel < MAXLEVEL; 
 77       newLevel++);
 78     /*如果大于当前的level,则更新update数组并更新当前level*/
 79     if (newLevel > list.listLevel) {
 80         for (i = list.listLevel + 1; i <= newLevel; i++)
 81             update[i] = NIL;
 82         list.listLevel = newLevel;
 83     }
 84 
 85     /* 给新节点分配空间,分配newLevel个指针,则这个
 86     节点的高度就固定了,只有newLevel。更高的层次将
 87     不会再有这个值*/
 88     if ((x = malloc(sizeof(nodeType) + newLevel*sizeof(nodeType *))) == 0)
 89         return STATUS_MEM_EXHAUSTED;
 90     x->key = key;
 91     x->rec = *rec;
 92 
 93     /* 给每层都加上这个值,相当于往链表中插入一个数*/
 94     for (i = 0; i <= newLevel; i++) {
 95         x->forward[i] = update[i]->forward[i];
 96         update[i]->forward[i] = x;
 97     }
 98     return STATUS_OK;
 99 }
100 
101 statusEnum delete(keyType key) {
102     int i;
103     nodeType *update[MAXLEVEL+1], *x;
104 
105    /*******************************************
106     *  delete node containing data from list  *
107     *******************************************/
108 
109     /* find where data belongs */
110     x = list.hdr;
111     for (i = list.listLevel; i >= 0; i--) {
112         while (x->forward[i] != NIL 
113           && compLT(x->forward[i]->key, key))
114             x = x->forward[i];
115         update[i] = x;
116     }
117 
118 
119     x = x->forward[0];
120 
121 
122     if (x == NIL || !compEQ(x->key, key)) return STATUS_KEY_NOT_FOUND;
123 
124     /* adjust forward pointers */
125     for (i = 0; i <= list.listLevel; i++) {
126         if (update[i]->forward[i] != x) break;
127         update[i]->forward[i] = x->forward[i];
128     }
129 
130     free (x);
131 
132     /* adjust header level */
133     while ((list.listLevel > 0)
134     && (list.hdr->forward[list.listLevel] == NIL))
135         list.listLevel--;
136 
137     return STATUS_OK;
138 }
139 
140 statusEnum find(keyType key, recType *rec) {
141     int i;
142     nodeType *x = list.hdr;
143 
144    /*******************************
145     *  find node containing data  *
146     *******************************/
147 
148     for (i = list.listLevel; i >= 0; i--) {
149         while (x->forward[i] != NIL 
150           && compLT(x->forward[i]->key, key))
151             x = x->forward[i];
152     }
153     x = x->forward[0];
154     if (x != NIL && compEQ(x->key, key)) {
155         *rec = x->rec;
156         return STATUS_OK;
157     }
158     return STATUS_KEY_NOT_FOUND;
159 }
160 
161 void initList() {
162     int i;
163 
164    /**************************
165     *  initialize skip list  *
166     **************************/
167 
168     if ((list.hdr = malloc(
169             sizeof(nodeType) + MAXLEVEL*sizeof(nodeType *))) == 0) {
170         printf ("insufficient memory (initList)/n");
171         exit(1);
172     }
173     for (i = 0; i <= MAXLEVEL; i++)
174         list.hdr->forward[i] = NIL;
175     list.listLevel = 0;
176 }
177 
178 int main(int argc, char **argv) {
179     int i, maxnum, random;
180     recType *rec;
181     keyType *key;
182     statusEnum status;
183 
184 
185     /* command-line:
186      *
187      *   skl maxnum [random]
188      *
189      *   skl 2000
190      *       process 2000 sequential records
191      *   skl 4000 r
192      *       process 4000 random records
193      *
194      */
195 
196     maxnum = 20;
197     random = argc > 2;
198 
199     initList();
200 
201     if ((rec = malloc(maxnum * sizeof(recType))) == 0) {
202         fprintf (stderr, "insufficient memory (rec)/n");
203         exit(1);
204     }
205     if ((key = malloc(maxnum * sizeof(keyType))) == 0) {
206         fprintf (stderr, "insufficient memory (key)/n");
207         exit(1);
208     }
209 
210     if (random) {
211         /* fill "a" with unique random numbers */
212         for (i = 0; i < maxnum; i++) key[i] = rand();
213         printf ("ran, %d items/n", maxnum);
214     } else {
215         for (i = 0; i < maxnum; i++) key[i] = i;
216         printf ("seq, %d items/n", maxnum);
217     }
218 
219     for (i = 0; i < maxnum; i++) {
220         status = insert(key[i], &rec[i]);
221         if (status) printf("pt1: error = %d/n", status);
222     }
223 
224     for (i = maxnum-1; i >= 0; i--) {
225         status = find(key[i], &rec[i]);
226         if (status) printf("pt2: error = %d/n", status);
227     }
228 
229     for (i = maxnum-1; i >= 0; i--) {
230         status = delete(key[i]);
231         if (status) printf("pt3: error = %d/n", status);
232     }
233     return 0;
234 }
View Code

转自:http://blog.csdn.net/topcoder1234/article/details/5841119

posted @ 2013-05-26 20:00  simon1024  阅读(185)  评论(0编辑  收藏  举报