数据结构与算法分析:确定性跳跃表

#include <iostream>
using namespace std;

template<typename T>
class DSL{
    //1-2-3确定性跳跃表
    //在有序链表中实现O(logN)操作
    //链接:两个元素间存在从一点指向另一点的链
    //间隙容量:高度为h的链接元素之间高度为h-1的元素的数量
    //1-2-3确定性跳跃表满足间隙容量为1或2或3
private:
    struct SkipNode{
        T data;
        SkipNode* right;
        SkipNode* down;
        SkipNode(const T& da=T(),SkipNode* r=nullptr,SkipNode* d=nullptr):data(da),right(r),down(d){};
    };


    T INFINITY;
    SkipNode* header;   //链表头节点,高度为无穷大
    SkipNode* bottom;
    SkipNode* tail;

public:
    explicit DSL(const T& inf):INFINITY(inf){
        bottom=new SkipNode();
        bottom->right=bottom->down=bottom;
        tail=new SkipNode(INFINITY);
        tail->right=tail;
        header=new SkipNode(INFINITY,tail,bottom);
    }
    bool contains(const T& x) const{
        SkipNode* current=header;
        bottom->data=x;
        for (;;){
            if (x<current->data) current=current->down;
            else if (x>current->data) current=current->right;
            //如果current到了最右下方,返回false即没找到,否则current还不是bottom的时候,current的data已经等于x了说明找到了
            else return current!=bottom;
        }
    }
    void insert(const T& x){
        SkipNode* current=header;
        bottom->data=x;
        while (current!=bottom){
            while (x>current->data) current=current->right;
            //间隔容量大于3的话在向下插入会破坏性质,需要调整结构
            if (current->down->right->right->data<current->data){
                current->right=new SkipNode(current->data,current->right,current->down->right->right);
                current->data=current->down->right->data;
            }
            else current=current->down;
        }
        if (header->right!=tail) header=new SkipNode(INFINITY,tail,header);
    }
};

int main(){
    DSL<int>* d=new DSL<int>(30);
    for (int i=0;i<15;i++) d->insert(i);
    if (d->contains(12)) cout << "yes" << endl;
    else cout << "no" << endl;
    if (d->contains(17)) cout << "yes" << endl;
    else cout << "no" << endl;

    d->insert(17);

    if (d->contains(17)) cout << "yes" << endl;
    else cout << "no" << endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_森罗万象

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值