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

#include 
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;
}

你可能感兴趣的:(学习笔记,链表,数据结构)