最近看redis,又看到了跳跃表,不记得什么时候在哪里做题遇到过,忍不住自己写了一个跳跃表。下面是一些核心代码。
//
// Created by ma on 2015/6/29.
//
#ifndef SKIPLIST_H_
#define SKIPLIST_H_
#include <stddef.h>
#define MAX_LEVEL 16
class Random{
public:
static int randlevel();
static bool rand();
private:
static long seeds;
};
class skiplistnode{
public:
skiplistnode(int key=-1, int value=-1);
skiplistnode* &forward(const size_t& i);
int key() { return _key;}
int value() { return _value;}
bool insert_after(skiplistnode* p,int i);
bool skip_after(int i);
private:
int _key;
int _value;
int level;
skiplistnode *_forward[MAX_LEVEL];
};
class skiplist {
public:
skiplist();
~skiplist();
bool Insert(const int& key,const int& value);
bool Delete(const int& key);
private:
int level;
skiplistnode *head;
};
#endif //SKIPLIST_H_
//
// Created by ma on 2015/6/29.
//
#include <stdlib.h>
#include <time.h>
#include <assert.h>
#include "skiplist.h"
skiplistnode *&skiplistnode::forward(const size_t &i) {
return _forward[i];
}
skiplistnode::skiplistnode(int key, int value) : _key(key), _value(value), level(0) {
for (int i = 0; i < MAX_LEVEL; ++i) {
_forward[i] = NULL;
}
}
bool skiplistnode::insert_after(skiplistnode *p, int i) {
p->forward(i) = this->forward(i);
this->forward(i) = p;
return true;
}
bool skiplistnode::skip_after(int i) {
skiplistnode *p = this->forward(i);
assert (p != NULL);
this->forward(i) = p->forward(i);
return true;
}
skiplist::skiplist() : level(MAX_LEVEL) {
head = new skiplistnode();
for (int i = 0; i < MAX_LEVEL; ++i) {
head->forward(i) = NULL;
}
}
skiplist::~skiplist() {
}
bool skiplist::Insert(const int &key, const int &value) {
skiplistnode *nodes[MAX_LEVEL];
skiplistnode *q;
skiplistnode *p = head;
for (size_t i = level; i >= 0; i--) {
while ((q = p->forward(i)) && (q->key() < key))
p = q;
nodes[i] = p;
}
if (q && (q->key() == key))
return false;
int k = Random::randlevel();
skiplistnode *newnode = new skiplistnode(key, value);
for (int j = 0; j < k; ++j) {
nodes[j]->insert_after(newnode, j);
}
return true;
}
bool skiplist::Delete(const int &key) {
skiplistnode *q;
skiplistnode *p = head;
for (size_t i = level; i >= 0; i--) {
while ((q = p->forward(i)) && (q->key() < key))
p = q;
if (q && (q->key() == key)) {
p->skip_after(i);
}
}
if (q && (q->key() == key))
delete (q);
return true;
}
long Random::seeds = 0;
bool Random::rand() {
srand(time(NULL) + seeds++);
return random() % 2;
}
int Random::randlevel() {
int level = 0;
while (rand())
level++;
level = level < MAX_LEVEL ? level : MAX_LEVEL;
return level;
}