#include <iostream>
#include <cassert>
#include <time.h>
using namespace std;
const int DefaultSize=100;
template <class E, class K>
struct SkipNode
{
E data;
SkipNode<E,K> * * link;
SkipNode(int size=DefaultSize)
{
link=new SkipNode<E,K>* [size];
assert(link);
}
~SkipNode() {delete[] link;}
};
template <class E, class K>
class SkipList
{
private:
int maxLevel;
int Levels;
K TailKey;
SkipNode<E,K>* head;
SkipNode<E,K>* tail;
SkipNode<E,K>* * last; //记录search时每条链上的最后一个元素
int Level();
SkipNode<E,K>* SaveSearch(K& k1);
public:
SkipList(K large, int maxLev=DefaultSize);
~SkipList();
bool Search(const K& k1, E& e1)const;
E& getData(SkipNode<E,K>* current)
{
if(current!=NULL)
return ¤t->data;
else
return NULL;
}
bool insert(const K k1, E& e1);
bool Remove(const K k1, E& e1);
};
template <class E, class K>
SkipList<E,K>::SkipList(K large, int maxLev)
{
maxLevel=maxLev;
Levels=0;
TailKey=large;
head=new SkipNode<E,K>(maxlevel+1);
tail=new SkipNode<E,K>(0);
last=new SkipNode<E,K>* [maxLevel+1];
tail->data=large;
for(int i=0; i<=maxLevel; i++)
head->link[i]=tail;
}
template <class E, class K>
SkipList<E,K>::~SkipList()
{
SkipNode<E,K>* next;
while(head!=tail)
{
next=head->link[0];
delete head;
head=next;
}
delete tail;
delete [] last;
}
template <class E, class K>
bool SkipList<E,K>::Search(const K &k1, E &e1) const
{
if(k1>TailKey)
return false;
SkipNode<E,K>* p=head;
for(int i=Levels; i>=0; i--)
{
while(p->link[i]->key < k1) //这里需要在具体实现函数里面重载'<'
p=p->link[i];
}
e1=p->link[0]->key;
return(e1==k1) ? true : false;
}
template <class E, class K>
SkipNode<E,K> *SkipList<E,K>::SaveSearch(K &k1)
{
if(k1>TailKey)
return false;
kipNode<E,K>* p=head;
for(int i=Levels; i>=0; i--)
{
while(p->link[i]->key < k1)
p=p->link[i];
last[i]=p;
}
return p->link[0];
}
template <class E, class K>
int SkipList<E,K>::Level() //产生一个随机的级别,该级别<maxLevel
{
int lev=0;
while(rand()<=RAND_MAX/2)
lev++;
return(lev<maxLevel) ? lev : maxLevel;
}
template <class E, class K>
bool SkipList<E,K>::insert(const K k1, E &e1)
{
if (k1 >= TailKey)
{
cerr << “关键码太大!” << endl;
return false;
}
SkipNode<E,K> *p = SaveSearch(k1);
if(p->data == e1)
{
cerr << "关键码重复!" << endl;
return false;
}
int lev=Level();
if(lev>Levels)
{
lev=++Levels;
last[lev]=head;
}
SkipNode<E,K>* newNode=new SkipNode<E,K>(lev+1);
newNode->data=e1;
for(int i=0; i<=lev; i++) //链入新结点
{
newNode->link[i]=last[i]->link[i];
last[i]->link[i]=newNode;
}
return true;
}
templete <class E, class K>
bool SkipList<E,K>::Remove(const K k1, E &e1)
{
if (k1 > TailKey)
{
cerr << “关键码太大!” << endl;
return false;
}
SkipNode<E,K> *p = SaveSearch(k1);
for(int i=0; i<=Levels && last[i]->link[i]==p; i++)
//逐级链摘下该结点,last[i]->link[i]==p是为了保证结点p存在第i级链
last[i]->link[i]=p->link[i];
while(Level>0 && head->link[Levels]==tail) //修改级数
Levels--;
e1=p->data;
delete p;
return true;
}