Skip list -- 跳跃表的插入删除搜索等ADT操作的实现与测试

来源:互联网 发布:阿沁淘宝 编辑:程序博客网 时间:2024/05/09 07:40

源代码如下:



#include <stdlib.h>#include <stdio.h>#define lgNmax 5typedef char Key;struct Item{Key key;};typedef struct STnode* link;struct STnode{Item item ; link *next; //多个链接域组成的数组  int sz ; // 该节点的链接数  };static link head ,z;static int N ;  //跳跃表的总结点数  static int lgN ; //跳跃表的最高层数  struct Item NULLitem; Key key(Item item){return item.key;} //新建一个节点  link NEW(Item item , int k){ //k:该节点的链接数  int i; link x = (link)malloc(sizeof*x); x->next = (link *)malloc(k*sizeof(link)); x->item = item; x->sz = k; for(i=0;i<k;i++)x->next[i]=z; return x; }  //初始化   void STinit(){  N = 0; lgN = 0;  z = NEW(NULLitem,RAND_MAX);  head = NEW(NULLitem,lgNmax + 1);  } //以概率1/2^j产生一个新的J个链接的节点  int randX(){  int i , j, t = rand(); for(i=1,j=2;i<lgNmax;i++,j+=j) if(t > RAND_MAX / j)break; if(i > lgN) lgN = i; return i; }  //跳跃表的插入操作  void insertR(link t, link x, int k){ //t:原跳跃表 x:带插入的节点 k:  跳跃表的最高层数 Key v = key(x->item), u = key(t->next[k]->item); if(v < u || u ==0){ if(k < x->sz){ //<= or < x->next[k] = t->next[k]; //插入操作  t->next[k] = x; }if(k==0) return;insertR(t,x,k-1);return; } insertR(t->next[k],x,k); }  //跳跃表的插入操作  void STinsert(Item item){ insertR(head , NEW(item,randX()),lgN); N++; } //跳跃表的删除操作  void deleteR(link t,Key v,int k){ link x = t->next[k]; if(!(key(x->item) < v) || key(x->item)==0){ if(v == key(x->item)) t->next[k] = x->next[k]; if(k==0){ free(x);return; } deleteR(t,v,k-1);return; } deleteR(t->next[k],v,k); } //跳跃表的删除操作  void STdelete(Key v){ deleteR(head, v, lgN);N--; }   Item searchR(link t, Key v, int k){ if(t==z) return NULLitem; if(v == key(t->item)) return t->item; Key u = key(t->next[k]->item); if(v < u || u ==0) if(k==0) return NULLitem; else return searchR(t,v,k-1); return searchR(t->next[k],v,k); }  Item STsearch(Key v){ return searchR(head , v,lgN); }   //打印跳跃表  void p(){ link t = head ; while(t->next[0] !=z){ printf("%c ",t->next[0]->item.key); t = t->next[0]; } printf("\n"); }    main(){ STinit(); struct Item item[10] = {'a','s','e','r','c','h','i','n','g','x'};int i;for(i=0;i<10;i++)STinsert(item[i]);p();struct Item i1 = STsearch('i');printf("%c\n",i1.key);STdelete('i');//printf("%c ",head->next[0]->item.key);p(); } 



运行结果





1 0
原创粉丝点击