Skip List Data Structure Code Implementations
Production-ready Skip List Data Structure data structure implementations in C++, Python, Java, and JavaScript on AntInLoop.
Study Skip List Data Structure Guide ยท Launch Visualizer
CPP Implementation
#include <iostream>
using namespace std;
// Node definition
struct Node
{
int data;
bool color;
Node *left, *right, *parent;
// Constructor
explicit Node(int data)
{
this->data = data;
left = right = parent = nullptr;
this->color = true; // true represents red, false represents black
}
};
// Class to represent Red-Black Tree
class RBTree
{
private:
Node *root;
protected:
void rotateLeft(Node *&, Node *&);
void rotateRight(Node *&, Node *&);
void fixViolation(Node *&, Node *&);
public:
// Constructor
RBTree() { root = nullptr; }
void insert(const int &n);
void inorder();
void levelOrder();
};
// A recursive function to do level order traversal
void inorderHelper(Node *root)
{
if (root == nullptr)
return;
inorderHelper(root->left);
cout << root->data << " ";
inorderHelper(root->right);
}
// A utility function to insert a new node with given data
Node* insertBST(Node* root, Node *pt)
{
/* If the tree is empty, assign a new node address to root */
if (root == nullptr)
return pt;
/* Else, do level order traversal until we find an empty
place, i.e. either left child or right child of some
node is pointing to NULL. */
if (pt->data < root->data)
{
root->left = insertBST(root->left, pt);
root->left->parent = root;
}
else if (pt->data > root->data)
{
root->right = insertBST(root->right, pt);
root->right->parent = root;
}
/* return the (unchanged) node pointer */
return root;
}
// Function to do inorder and level order traversals
void RBTree::inorder() { inorderHelper(root);}
void RBTree::levelOrder() { levelOrderHelper(root); }
// Function to insert a new node with given data
void RBTree::insert(const int &data)
{
Node *pt = new Node(data);
// Do a normal BST insert
root = insertBST(root, pt);
// fix Red Black Tree violations
fixViolation(root, pt);
}
// main function
int main()
{
RBTree tree;
tree.insert(7);
tree.insert(6);
tree.insert(5);
tree.insert(4);
tree.insert(3);
tree.insert(2);
tree.insert(1);
cout << "Inorder Traversal of Created Tree\
";
tree.inorder();
cout << "\
\
Level Order Traversal of Created Tree\
";
tree.levelOrder();
return 0;
}