#ifndef SKIPLIST_H_INCLUDED
#define SKIPLIST_H_INCLUDED
const int maxLevel = 5;
template<class T>
struct SLNode{
int level; //当前节点在跳表的层数
T data;
SLNode<T> *next; //指向同一层的下一个节点
SLNode<T> *down; //指向下一层的节点
SLNode<T>(T x):data(x){next = NULL;down = NULL;}
};
template<class T>
class SkipList{
private:
int level; //跳表的层数
SLNode<T> *first; //最高的第一个节点
public:
SkipList(int l);
~SkipList();
bool Insert(T x,int l);
void Print();
bool find(T x,int &l); //查找元素x是否存在,若存在l返回节点所在level,否则l返回-1
};
template<class T>
SkipList<T>::SkipList(int l){//构造函数
level = l;
first = new SLNode<T>(-1);
first->level = level;
SLNode<T> *p = first;
for(int i = 1; i < level; i++){ //构造指定每一层的头结点
p->down = new SLNode<T>(-1);
p = p->down;
p->level = level-i;
}
}
template<class T>
SkipList<T>::~SkipList(){
SLNode<T> *p = first,*q,*t;
while(p != NULL){
q = p->next;
while(q != NULL){ //删除以q为头结点的层
t = q;
q = q->next;
delete t;
}
t = p;
p = p->down; //指向下一层
delete t;
}
}
template<class T>
bool SkipList<T>::Insert(T x,int l){ //将x插入到第l层
if(level < l)return false;
SLNode<T> *p,*q,*q1,*r = NULL; int i;
p = first;
for(i = level; i > l && p != NULL; i--){ //找到要插入的层
p = p->down;
}
if(p == NULL) return false;
for(; i >= 1; i--){ //依次插入到下一层
q1 = p;q = p->next;
while(q != NULL && q->data < x){ //找到每一层的插入位置
q1 = q1->next;
q = q->next;
}
if(q == NULL){ //插入的位置为空,即插入到层的尾端
q1->next = new SLNode<T>(x);
q1->next->level = i;
if(r != NULL)
r->down = q1->next; //r记录跳表上一层插入的位置,用于链接不同层之间大小相同的节点
r = q1->next; //更新r记录当前层插入的位置
}
else if(q->data == x){ //删除该判断可以实现元素重复的跳表
r->down = q;
r = q;
}
else{ //若插入的位置不为空,创建新节点并插入
SLNode<T> *t = new SLNode<T>(x);
t->next = q;
q1->next = t;
t->level = p->level;
if(r != NULL)
r->down = t;
r = t; //更新r的值,指向当前层插入的位置
}
p = p->down; //当前层插入完毕,进入下一层,p指向下一层的头结点
}
return true;
}
template<class T>
void SkipList<T>::Print(){
SLNode<T> *p = first,*q;
for(int i = 0; i < level; i++){ //逐层打印节点
q = p->next; //每一层逐个节点打印
cout << "level:" << p->level << " ";
while(q != NULL){
cout << q->data << " ";
q = q->next;
}
cout << endl;
p = p->down; //进入下一层
}
}
template<class T>
bool SkipList<T>::find(T x,int &l){ //在跳表中查询大小与节点x存储的值相同的节点,l返回x所在层数(层数由下而上增大),若不存在<span style="white-space:pre"> </span>//返回-1
SLNode<T> *p = first,*q;
while(p != NULL){
q = p;
while(p != NULL && p->data < x ){q = p;p = p->next;}
if(p == NULL){p = q->down;cout << "p指向了" << p->data << "level:" << p->level << endl;}
else if(p->data == x){l = p->level;return true;}
else p = q->down;
}
l = -1; return false;
}
#endif // SKIPLIST_H_INCLUDED
跳表的实现
最新推荐文章于 2024-06-07 00:45:43 发布