Advertisement
pavelperc

insert_skiplist

Nov 8th, 2018
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.09 KB | None | 0 0
  1.  
  2. template<class Value, class Key, int numLevels>
  3. void SkipList<Value, Key, numLevels>::insert(const Value &val, const Key &key)
  4. {
  5.     Node* newNode = new Node(key, val);
  6.     Node* prevNode;
  7.  
  8.     std::cout << "doing INS of key " << key << std::endl;
  9.     if (this->_preHead->next == this->_preHead)
  10.     {
  11.         this->_preHead->next = newNode;
  12.         newNode->next = this->_preHead;
  13.     }
  14.     else
  15.     {
  16.         prevNode = findLastLessThan(key);
  17.        
  18.         // move right a bit among equal nodes
  19.         while (prevNode->next != this->_preHead && prevNode->next->key == key)
  20.             prevNode = prevNode->next;
  21.        
  22.         newNode->next = prevNode->next;
  23.         prevNode->next = newNode;
  24.     }
  25.  
  26.     int currentLevel = -1;
  27.  
  28.     // std::rand() генерирует числа [0, RAND_MAX]. Превращаем их в отрезок от 0 до 1 и радуемся.
  29.     // Высчитываем, на каком уровне у нас впервые встретится элемент
  30.     float prob = (float) std::rand() / RAND_MAX;
  31.  
  32. //    std::cout << "Prob is " << prob << "\n";
  33.     while (currentLevel < numLevels - 1 && prob < _probability)
  34.     {
  35.         ++currentLevel;
  36.         prob = (float) std::rand() / RAND_MAX;
  37. //        std::cout << "And now prob is " << prob << "\n";
  38.     }
  39.    
  40.     // adding references on higher levels
  41.     using namespace std;
  42.     newNode->levelHighest = currentLevel;
  43.     Node* currentNode = this->_preHead;
  44.  
  45.     while (currentLevel != -1)
  46.     {
  47.         // right in sparse levels!
  48.         Node* right = currentNode->nextJump[currentLevel];
  49.        
  50.         // our new node is the last among all equal to it, (so <= )
  51.         if (right != this->_preHead && right->key <= key)
  52.         {
  53.             // just go right
  54.             currentNode = right;
  55.         }
  56.         else
  57.         {
  58.             // insert new reference in sparse level.
  59.             currentNode->nextJump[currentLevel] = newNode;
  60.             newNode->nextJump[currentLevel] = right;
  61.             // go down            
  62.             --currentLevel;
  63.         }
  64.     }
  65.  
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement