SkipList简单demo(C++)实现

#include 
#include 
#include 
#include 
#include 

#define MAX_LEVEL 6  // 最大层数

class Node {
public:
    int m_value;
    std::vector m_forward; // 表示当前节点在第 i 层的“下一个”节点

    Node(int value, int level) : m_value(value), m_forward(level, nullptr) {}
};

class SkipList {
private:
    int m_level;    // 当前跳表的高度
    Node* m_header;

    int randomLevel() {
        int lvl = 1;
        while ((rand() % 2) && lvl < MAX_LEVEL) {
            lvl++;
        }
        return lvl;
    }

public:
    SkipList() {
        m_level = 1;
        m_header = new Node(-1, MAX_LEVEL); // -1为哨兵头节点
        srand(time(nullptr));
    }

    void insert(int value) {
        std::vector update(MAX_LEVEL, nullptr);  // 记录每一层要修改的前驱节点
        Node* curr = m_header;

        // 从高层往下查找插入位置
        for (int i = m_level - 1; i >= 0; i--) {
            while (curr->m_forward[i] && curr->m_forward[i]->m_value < value) {
                // 在第 i 层中找到 value 插入位置的前驱节点
                curr = curr->m_forward[i];
            }
            // 记录第 i 层中 value 的前驱节点
            update[i] = curr;
        }

        int newLevel = randomLevel();
        if (newLevel > m_level) {
            for (int i = m_level; i < newLevel; i++) {
                update[i] = m_header;
            }
            m_level = newLevel;
        }

        Node* newNode = new Node(value, newLevel);

        // 将新的节点插入到每一层中
        for (int i = 0; i < newLevel; i++) {
            newNode->m_forward[i] = update[i]->m_forward[i];
            update[i]->m_forward[i] = newNode;
        }

        std::cout << "Inserted " << value << " at level " << newLevel << std::endl;
    }

    bool search(int value) {
        Node* curr = m_header;
        for (int i = m_level - 1; i >= 0; i--) {
            // 在第 i 层中找到 < value 的前驱节点,然后跳转到下一层,直到第0层
            while (curr->m_forward[i] && curr->m_forward[i]->m_value < value) {
                curr = curr->m_forward[i];
            }
        }
        // 找到了第0层中 value 的位置,判断该位置上的节点值是否为value
        curr = curr->m_forward[0];
        return curr && curr->m_value == value;
    }

    void printList() {
        for (int i = m_level - 1; i >= 0; i--) {
            Node* node = m_header->m_forward[i];
            std::cout << "Level " << i + 1 << ": ";
            while (node) {
                std::cout << node->m_value << " ";
                node = node->m_forward[i];
            }
            std::cout << "\n";
        }
    }
};

int main() {
    SkipList list;

    list.insert(3);
    list.insert(6);
    list.insert(7);
    list.insert(9);
    list.insert(12);
    list.insert(19);

    list.printList();

    std::cout << "Search 7: " << (list.search(7) ? "Found" : "Not Found") << std::endl;
    std::cout << "Search 8: " << (list.search(8) ? "Found" : "Not Found") << std::endl;

    return 0;
}

你可能感兴趣的:(c++,skiplist,开发语言)