class Skiplist {
public:
static constexpr int MAX_LEVEL = 16;
static constexpr double P = 0.6;
//随机数产生相关,#include<random>,详见cppreference
std::random_device rd;
std::mt19937 gen;
std::uniform_real_distribution<> dis;
struct node
{
int data;
node *next[MAX_LEVEL+1];
node()
{
for(int i=1;i<=MAX_LEVEL;i++)
next[i] = NULL;
}
};
node *head;
Skiplist() {
head = new node;
gen = std::mt19937(rd());
dis = std::uniform_real_distribution<> (0,1);
}
int randomLevel()
{
int ret = 1;
while(ret<MAX_LEVEL && dis(gen)<P)
ret++;
return ret;
}
bool search(int target) {
node *now = head;
for(int i=MAX_LEVEL;i>=1;i--)
while(now->next[i] != NULL && now->next[i]->data<target) now = now->next[i];
if(now->next[1] == NULL) return false;
if(now->next[1]->data != target) return false;
return true;
}
void add(int num) {
node *tmp = new node;
tmp->data = num;
node *pre[MAX_LEVEL+1];//前驱
node *now = head;
int level = randomLevel();
for(int i=MAX_LEVEL;i>=1;i--)
{
while(now->next[i] != NULL && now->next[i]->data<num) now = now->next[i];
pre[i] = now;
}
for(int i=level;i>=1;i--)
{
tmp->next[i] = pre[i]->next[i];
pre[i]->next[i] = tmp;
}
}
bool erase(int num) {
node *pre[MAX_LEVEL+1];
node *now = head;
for(int i=MAX_LEVEL;i>=1;i--)
{
while(now->next[i] != NULL && now->next[i]->data<num) now = now->next[i];
pre[i] = now;
}
if(now->next[1] == NULL) return false;
if(now->next[1]->data !=num) return false;
for(int i=MAX_LEVEL;i>=1;i--)
{
if(pre[i]->next[i]!=NULL)pre[i]->next[i] = pre[i]->next[i]->next[i];
else pre[i]->next[i]=NULL;
}
return true;
}
};
参考文献