跳表skipList的C++泛型编程实现

目前刚写完,还没有完全进行测试,欢迎批评指正

#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;
}
  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值