template <typename Key, classComparator> void SkipList<Key, Comparator>::Insert(const Key& key) { // TODO(opt): We can use a barrier-free variant of FindGreaterOrEqual() // here since Insert() is externally synchronized. Node* prev[kMaxHeight]; Node* x = FindGreaterOrEqual(key, prev); // 找插入的位置
// Our data structure does not allow duplicate insertion assert(x == nullptr || !Equal(key, x->key));
int height = RandomHeight(); // 决定新node的高度 if (height > GetMaxHeight()) { for (int i = GetMaxHeight(); i < height; i++) { // 如果高度大于目前最高,就设置prev为头节点 prev[i] = head_; } max_height_ = height; // 此处有改动 }
x = NewNode(key, height); // 创建新的node for (int i = 0; i < height; i++) { x->NoBarrier_SetNext(i, prev[i]->NoBarrier_Next(i)); prev[i]->SetNext(i, x); } }