跳表通过多层链表实现O(log n)平均时间复杂度的查找、插入和删除,结构简单,代码清晰,适合手写有序集合。

跳表(Skip List)是一种基于概率的有序数据结构,能以平均 O(log n) 的时间复杂度实现查找、插入和删除操作,实现简单且性能接近平衡树。相比红黑树或AVL树,跳表代码更清晰,适合手写实现一个有序集合。
跳表的基本原理
跳表通过多层链表实现快速跳跃。底层是完整的有序链表,每一层是下一层的“快照”,包含部分节点。查找时从顶层开始,横向移动到合适位置后下降一层,逐步逼近目标。
每个节点有多个指针(层数随机决定),高层用于跳过大量节点,低层用于精细定位。插入时通过随机函数决定该节点的层数,维持整体平衡。
节点结构设计
定义跳表节点,包含值和指向各层下一个节点的指针数组:
template struct SkipListNode { T value; std::vector next;SkipListNode(T val, int level) : value(val), next(level, nullptr) {}
};
next[i] 表示该节点在第 i 层的下一个节点指针。level 在节点创建时确定。
立即学习“C++免费学习笔记(深入)”;
跳表类主体实现
核心成员包括最大层数、当前层数、头节点和随机策略:
template class SkipList {private: static const int MAX_LEVEL = 16; // 最大层数 int level; SkipListNode* head; std::random_device rd; std::mt19937 gen; std::uniform_int_distribution dis;int randomLevel() { int lvl = 1; while (lvl < MAX_LEVEL && dis(gen) % 2 == 0) { lvl++; } return lvl;}
public:SkipList() : level(1), gen(rd()), dis(0, 1) {head = new SkipListNode(T(), MAX_LEVEL);}
查找操作
从最高层开始,向右直到下一个节点大于目标,然后下降一层继续:
bool find(const T& val) { SkipListNode* curr = head; for (int i = level - 1; i >= 0; i--) { while (curr->next[i] && curr->next[i]->value next[i]; } } curr = curr->next[0]; return curr && curr->value == val;}
插入操作
先查找路径并记录每层最后到达的节点,再生成随机层数,更新各层指针:
void insert(const T& val) { std::vector<SkipListNode*> update(MAX_LEVEL, nullptr); SkipListNode* curr = head;for (int i = level - 1; i >= 0; i--) { while (curr->next[i] && curr->next[i]->value next[i]; } update[i] = curr;}curr = curr->next[0];if (curr && curr->value == val) return; // 已存在int newLevel = randomLevel();if (newLevel > level) { for (int i = level; i < newLevel; i++) { update[i] = head; } level = newLevel;}SkipListNode* newNode = new SkipListNode(val, newLevel);for (int i = 0; i next[i] = update[i]->next[i]; update[i]->next[i] = newNode;}
}
删除操作
查找节点并记录路径,若存在则逐层断开指针:
bool erase(const T& val) { std::vector<SkipListNode*> update(MAX_LEVEL, nullptr); SkipListNode* curr = head;for (int i = level - 1; i >= 0; i--) { while (curr->next[i] && curr->next[i]->value next[i]; } update[i] = curr;}curr = curr->next[0];if (!curr || curr->value != val) return false;for (int i = 0; i next[i] != curr) break; update[i]->next[i] = curr->next[i];}delete curr;while (level > 1 && head->next[level - 1] == nullptr) { level--;}return true;
}
完整性和使用示例
加上析构函数释放内存,即可使用:
~SkipList() { SkipListNode* curr = head; while (curr) { SkipListNode* next = curr->next[0]; delete curr; curr = next; }}// 示例int main() {SkipList sl;sl.insert(3);sl.insert(1);sl.insert(4);sl.insert(2);std::cout << sl.find(3) << std::endl; // 输出 1sl.erase(3);std::cout << sl.find(3) << std::endl; // 输出 0return 0;}
基本上就这些。跳表实现比红黑树简洁得多,调试也更容易。只要控制好随机层数上限和概率分布,性能非常稳定,适合作为有序集合的手写方案。
以上就是C++怎么实现一个跳表(Skip List)_C++实现堪比平衡树的有序集合数据结构的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1488770.html
微信扫一扫
支付宝扫一扫