link
class Skiplist {
public:
struct Node{
int key;
Node* down;
Node* next;
Node(int k, Node* d, Node *n){
key=k;
down=d;
next=n;
}
};
Node* head;
Skiplist() {
head=new Node(-1,NULL,NULL);
}
bool search(int target) {
Node* p=head;
while(p){
Node* ne=p->next;
while(ne!=NULL && ne->key<target){
p=p->next;
ne=ne->next;
}
if(ne!=NULL && target==ne->key) return true;
p=p->down;
}
return false;
}
void add(int num) {
vector<Node*> nodes;
Node* p=head;
Node* downNode=NULL;
while(p){
Node* ne=p->next;
while(ne!=NULL && num>ne->key){
p=p->next;
ne=ne->next;
}
nodes.push_back(p);
p=p->down;
}
for(int i=nodes.size()-1;i>=0;--i){
auto cur=nodes[i];
Node* newNode=new Node(num,downNode,NULL);
newNode->next=cur->next;
cur->next=newNode;
downNode=newNode;
bool up=((rand()&1)==0);
if(!up) break;
if(i==0){
Node* newLayerNode=new Node(num,downNode,NULL);
head=new Node(-1,head,newLayerNode);
}
}
}
bool erase(int num) {
bool flag=false;
Node* p=head;
while(p){
Node* ne=p->next;
while(ne!=NULL && num>ne->key){
p=p->next;
ne=ne->next;
}
if(ne!=NULL && num==ne->key){
p->next=p->next->next;
flag=true;
}
p=p->down;
}
return flag;
}
};
/**
* Your Skiplist object will be instantiated and called as such:
* Skiplist* obj = new Skiplist();
* bool param_1 = obj->search(target);
* obj->add(num);
* bool param_3 = obj->erase(num);
*/