A skip list is a data structure that allows for search and insertion in O(log n) time complexity, similar to a balanced binary search tree, but with simpler implementation. It consists of a hierarchy of linked lists with increasingly fewer elements, with each node in a higher-level list skipping over sections of lower-level lists. Here's an implementation of a skip list in Swift:
main.swift1762 chars71 lines
In this implementation, Node
represents a single element in the skip list with a value and an array of next
pointers to elements at the same level and in lower levels. SkipList
maintains a few parameters:
maxLevel
: the maximum level of the skip listp
: the probability of increasing a node levelhead
: the node at the top level with no valuelevel
: the current highest level in the skip listThe insert
method creates a new node with a randomized level, traverses the skip list to find the correct insertion point and update references to point to the new node at all levels up to its level. The contains
method traverses the skip list from the highest level to the lowest, searching for nodes with the target value. The randomLevel
method uses a bounded random number generator to simulate a coin flip with probability p
of returning heads, until a maximum level is reached.
Note that this implementation assumes all inserted values are unique. To support duplicates, the contains
method could return a count of nodes with the target value instead of a binary result, and the insert
method could find the insertion point for the new node by comparing its value to the value of the last node at each level instead of skipping over higer-value nodes.
gistlibby LogSnag