voidInsert(int key) { auto record = vector<shared_ptr<Node>>(MAXLEVEL + 1); shared_ptr<Node> cur = header;
for (int i = level; i >= 0; i--) { while (cur->forward[i] != nullptr && cur->forward[i]->key < key) cur = cur->forward[i]; record[i] = cur; } cur = cur->forward[0]; // 节点已存在则直接返回 if (cur != nullptr && cur->key == key) return;
// 创建一个新的节点 n 进行更新 int rLevel = RandomLevel(); shared_ptr<Node> n = make_shared<Node>(key, rLevel); for (int i = 0; i <= rLevel; i++) { if (i <= level) { n->forward[i] = record[i]->forward[i]; record[i]->forward[i] = n; } else header->forward[i] = n; }
level = max(level, rLevel); }
删除
我们考虑删除一个值为 key 的节点。
我们从最上层开始走,每次找到当前层最后一个值比 key 小的节点,然后从这个节点的位置进入下一层。在这个过程中,我们对于第 i 层记录下这个节点 record[i],方便后面的更新。
然后我们跳转到原链表,判断一下是否存在值为 key 的节点,若存在我们假设它为 cur。
我们从原链表开始一层一层往上走,进行删除。显然我们对于 record[i]→forward[i] 是 cur 的节点,我们直接将 record[i]→forward[i] 设置为 cur→forward[i];如果不是,则说明 cur 并没有被上放到该层,可以停止操作。
// 随机生成一个节点最高的层数 intRandomLevel() { int rLevel = 0; while ((float)rand() / RAND_MAX < P && rLevel < MAXLEVEL) { rLevel++; } return rLevel; }
boolSearch(int key) { shared_ptr<Node> cur = header;
// 从最高层级开始走,找到当前层最后一个比 key 值小的节点 for (int i = level; i >= 0; i--) { while (cur->forward[i] != nullptr && cur->forward[i]->key < key) cur = cur->forward[i]; }
// 跳转到原链表,然后往后一个位置 cur = cur->forward[0]; return cur != nullptr && cur->key == key; }
voidInsert(int key) { auto record = vector<shared_ptr<Node>>(MAXLEVEL + 1); shared_ptr<Node> cur = header;
for (int i = level; i >= 0; i--) { while (cur->forward[i] != nullptr && cur->forward[i]->key < key) cur = cur->forward[i]; record[i] = cur; } cur = cur->forward[0]; // 节点已存在则直接返回 if (cur != nullptr && cur->key == key) return;
// 创建一个新的节点 n 进行更新 int rLevel = RandomLevel(); shared_ptr<Node> n = make_shared<Node>(key, rLevel); for (int i = 0; i <= rLevel; i++) { if (i <= level) { n->forward[i] = record[i]->forward[i]; record[i]->forward[i] = n; } else header->forward[i] = n; }
level = max(level, rLevel); }
voidDelete(int key) { auto record = vector<shared_ptr<Node>>(MAXLEVEL + 1); shared_ptr<Node> cur = header;
for (int i = level; i >= 0; i--) { while (cur->forward[i] != nullptr && cur->forward[i]->key < key) { cur = cur->forward[i]; } record[i] = cur; } cur = cur->forward[0]; // 节点不存在 或 值不为 key 则直接返回 if (cur == nullptr || cur->key != key) return;
for (int i = 0; i <= level; i++) { if (record[i]->forward[i] == nullptr || record[i]->forward[i]->key != key) break; record[i]->forward[i] = cur->forward[i]; }