赞
踩
不懂跳跃表的请直接百度
直接上实现
#include <iostream> #include <string.h> #include <ctime> using namespace std; template<typename T> struct SkipNode { inline static constexpr int Rate=3; inline static constexpr int MaxHeight=8; inline static constexpr intmax_t Inf= INT_MAX; inline static SkipNode<T>* update[MaxHeight]; intmax_t key; T val; SkipNode<T> *pre[MaxHeight], *nex[MaxHeight]; SkipNode<T>(intmax_t k=Inf,const T& v = {}) : key(k), val(v) { init_pos(nullptr); } auto init_pos(SkipNode<T>* ptr=nullptr) { for (int h=0; h<MaxHeight; ++h) { pre[h]=nex[h]=ptr; } return this; } SkipNode<T>* escape() { for(int h=0; h<MaxHeight; ++h) { auto *p=pre[h], *x=nex[h]; pre[h]=nex[h]=nullptr; if(p)p->nex[h]=x; if(x)x->pre[h]=p; } return this; } intmax_t upper_bound(intmax_t key__, SkipNode<T> *(&update__)[MaxHeight]=update) { memset(update__,0,sizeof(update__)); auto *p = this; for(int h=MaxHeight-1; h>=0; --h) { while(p->nex[h] && p->nex[h]!=this && p->nex[h]->key > key__) p=p->nex[h]; update__[h]=p; } return p->nex[0] ? p->nex[0]->key : Inf; } void into(SkipNode<T> *(&update__)[MaxHeight]=update) { this->init_pos(nullptr); for(int h=0; h<MaxHeight; ++h) { if (update__[h]) { auto *x = update__[h]->nex[h]; update__[h]->nex[h]=this; this->nex[h]=x; if(x)x->pre[h]=this; if(this)this->pre[h]=update__[h]; } if(rand()%Rate) break; } } void print() { for(auto *p = this->nex[0]; p && p!=this; p=p->nex[0]) { cout << "("<<p->key << ":" << p->val<<"), "; } endl(cout); } }; template<typename ValType> void skiplist_insert(SkipNode<ValType> &hand,intmax_t key,ValType val) { decltype(hand.update) assist{}; if(key == hand.upper_bound(key,assist)) { assist[0]->nex[0]->val = val; } else { (new SkipNode<ValType>(key,val))->into(assist); } } template<typename ValType> bool skiplist_erase(SkipNode<ValType> &hand,intmax_t key) { decltype(hand.update) assist{}; if (key == hand.upper_bound(key,assist)) { delete assist[0]->nex[0]->escape(); return true; } return false; } void test_insert0() { SkipNode<int> hand; hand.init_pos(&hand); srand(time(0)); skiplist_insert<int>(hand,32,78); skiplist_insert<int>(hand,36,78); skiplist_insert<int>(hand,32,71); skiplist_insert<int>(hand,33,78); skiplist_insert<int>(hand,311,766); hand.print(); } void test_erase0() { SkipNode<int> hand; hand.init_pos(&hand); srand(time(0)); skiplist_insert<int>(hand,32,78); skiplist_insert<int>(hand,36,78); skiplist_insert<int>(hand,32,71); skiplist_insert<int>(hand,33,78); skiplist_insert<int>(hand,311,766); hand.print(); skiplist_erase(hand,100); hand.print(); skiplist_erase(hand,311); hand.print(); } int main() { test_insert0(); test_erase0(); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。