#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std; // TESTING ONLY
class SkipList
{
private:
struct Node
{
Node(int value, int level)
{
this->value = value;
next = new Node*[level];
}
Node **next;
int value;
};
Node *head = new Node(0, maxLevel);
int maxLevel;
public:
SkipList()
{
maxLevel = 10;
srand((int)time(nullptr));
head->next = new Node*[maxLevel];
for (int i = 0; i < maxLevel; i++)
{
head->next[i] = nullptr;
}
}
int promotion()
{
int level = 0;
int _rand = rand() % 2;
while (_rand)
{
level++;
_rand = rand() % 2;
}
return level;
}
void Insert(int value)
{
int level = promotion();
Node *newNode = new Node(value, level);
Node *curr = head;
for (int i = 9; i >= 0; i--)
{
if (curr->next[i] != nullptr)
{
while (value > curr->next[i]->value && curr->next[i]->next[i] != nullptr)
{
curr = curr->next[i];
}
}
}
for (int i = 0; i <= level; i++)
{
newNode->next[i] = curr->next[i];
curr->next[i] = newNode;
}
}
void print() const
{
Node *cur = head->next[0];
cout << "List: NULL --> ";
while (cur != nullptr)
{
cout << cur->value << " --> ";
cur = cur->next[0];
}
cout << "NULL";
cout << endl;
}
};
int main()
{
SkipList skip;
skip.Insert(3);
skip.Insert(2);
skip.Insert(50);
skip.Insert(39);
skip.Insert(2000);
skip.Insert(500);
skip.print();
cout << endl << endl;
system("pause"); // TESTING
return 0;
}
上記のコードを実行すると、挿入された最初の要素 (この例では 3) は常にリストの最後の要素になります。他のすべての要素は正しい順序で挿入されます。上記のプログラムは、2-39-50-500-2000-3 を表示します。さらに 100 個の値を挿入すると、より大きな値を配置しても、挿入された最初の要素が常に最後になることを除いて、それらはすべて正しい位置に挿入されます。
指を置くことはできませんが、挿入を配置するときにリストの最後の要素を無視していることは明らかです。誰かがこれに光を当てることができれば感謝します。ありがとう!