目前刚写完,还没有完全进行测试,欢迎批评指正
#include <iostream>
using namespace std;
constexpr int max_depth=24;
template <typename K,typename V>
struct listNode
{
K key_;
V val_;
vector<listNode<K,V>*>next;
listNode(K key,V val,int depth=max_depth):key_(key),val_(val),next(depth+1,nullptr){}
listNode():next(max_depth+1,nullptr){}
};
template <typename K,typename V>
class skipList
{
private:
listNode<K,V> *head;
int depth;
public:
skipList():head(new listNode<K,V>()),depth(1){}
bool search(K key)
{
listNode<K,V> *cur=head;
for(int i=depth;i>=1;i--)
{
while(cur->next[i]&&cur->next[i]->key_<key)
{
cur=cur->next[i];
}
}
listNode<K,V>*curr=cur->next[1];
if(curr&&curr->key_==key)
{
return true;
}
return false;
}
void insert(K key,V val)
{
vector<listNode<K,V>*> tmp(max_depth+1,nullptr);
listNode<K,V> *cur=head;
for(int i=depth;i>=1;i--)
{
while(cur->next[i]&&cur->next[i]->key_<key)
{
cur=cur->next[i];
}
tmp[i]=cur;
}
listNode<K,V>*curr=cur->next[1];
if(curr&&curr->key_==key)
{
curr->val_=val;
return;
}
int n=getRandDepth();
depth=max(n,depth);
listNode<K,V> *new_node=new listNode(key,val,n);
for(int i=n;i>=1;i--)
{
new_node->next[i]=tmp[i]->next[i];
tmp[i]->next[i]=new_node;
}
}
bool remove(K key)
{
vector<listNode<K,V>*> tmp(max_depth+1,nullptr);
listNode<K,V> *cur=head;
for(int i=depth;i>=1;i--)
{
while(cur->next[i]&&cur->next[i]->key_<key)
{
cur=cur->next[i];
}
tmp[i]=cur;
}
listNode<K,V>*curr=cur->next[1];
if(curr==nullptr||curr->key_!=key)
{
return false;
}
for(int i=1;i<depth;i++)
{
if(tmp[i]->next[0]!=curr)
{
break;
}
tmp[i]->next[i]=curr->next[i];
}
delete curr;
while(depth>1&&head->next[depth]==nullptr)
{
depth--;
}
return true;
}
int getRandDepth(void)
{
int tmp=1;
while(tmp<max_depth&&rand()%4==0)
{
tmp++;
}
return tmp;
}
};
int main()
{
skipList<int,int> skp;
skp.insert(1,2);
skp.insert(2,3);
if(skp.search(2))
{
cout<<"True"<<endl;
}
return 0;
}