~kjiwa

Skip List

June 2011

Skip lists are a data structure that can be used in place of balanced trees. Skip lists use probabilistic balancing rather than strictly enforced balancing and as a result the algorithms for insertion and deletion in skip lists are much simpler and significantly faster than equivalent algorithms for balanced trees. (Pugh)

My implementation was based on William Pugh’s original paper, which you can download here. Despite being called a list, the structure described in the paper has the interface of a dictionary, with each node containing a comparable key and a value. A more complete implementation of the skip list that implements java.util.Map is available under the MIT license on GitHub.

SkipList.java
/*
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
import java.util.*;

public class SkipList<K extends Comparable<K>, V> {
    private double p;
    private Node<K, V> head;
    private Node<K, V> tail;
    private int level;
    private int size;
    private Random r;

    public SkipList(double p) {
        this.p = p;
        head = new Node<K, V>(null, null);
        tail = new Node<K, V>(null, null);
        r = new Random();
        clear();
    }

    public SkipList() {
        this(0.5);
    }

    public void clear() {
        head.forward.clear();
        head.forward.put(0, tail);
        level = 1;
        size = 0;
    }

    public V get(Object key) {
        @SuppressWarnings("unchecked")
        K k = (K) key;
        if (k == null) {
            throw new NullPointerException();
        }

        Node<K, V> cur = head;
        for (int i = level - 1; i >= 0; --i) {
            while (!cur.forward.get(i).equals(tail) && cur.forward.get(i).key.compareTo(k) < 0) {
                cur = cur.forward.get(i);
            }
        }

        cur = cur.forward.get(0);
        if (!cur.equals(tail) && cur.key.equals(k)) {
            return cur.value;
        }

        return null;
    }

    public V put(K key, V value) {
        Map<Integer, Node<K, V>> update = new HashMap<>();
        Node<K, V> cur = head;
        for (int i = level - 1; i >= 0; --i) {
            while (!cur.forward.get(i).equals(tail) && cur.forward.get(i).key.compareTo(key) < 0) {
                cur = cur.forward.get(i);
            }

            update.put(i, cur);
        }

        cur = cur.forward.get(0);
        if (!cur.equals(tail) && cur.key.equals(key)) {
            V prev = cur.value;
            cur.value = value;
            return prev;
        }

        int newLevel = randomLevel();
        if (newLevel > level) {
            for (int i = level; i < newLevel; ++i) {
                update.put(i, head);
                head.forward.put(i, tail);
            }

            level = newLevel;
        }

        cur = new Node<>(key, value);
        for (int i = 0; i < newLevel; ++i) {
            Node<K, V> prev = update.get(i);
            cur.forward.put(i, prev.forward.get(i));
            prev.forward.put(i, cur);
        }

        ++size;
        return null;
    }

    public V remove(Object key) {
        @SuppressWarnings("unchecked")
        K k = (K) key;
        if (k == null) {
            throw new NullPointerException();
        }

        Map<Integer, Node<K, V>> update = new HashMap<>(level);
        Node<K, V> cur = head;
        for (int i = level - 1; i >= 0; --i) {
            while (!cur.forward.get(i).equals(tail) && cur.forward.get(i).key.compareTo(k) < 0) {
                cur = cur.forward.get(i);
            }

            update.put(i, cur);
        }

        cur = cur.forward.get(0);
        if (cur.equals(tail) || !cur.key.equals(k)) {
            return null;
        }

        for (int i = 0; i < level; ++i) {
            Node<K, V> prev = update.get(i);
            if (!prev.forward.get(i).equals(cur)) {
                break;
            }

            prev.forward.put(i, cur.forward.get(i));
        }

        while (level > 1 && head.forward.get(level - 1).equals(tail)) {
            head.forward.remove(level - 1);
            --level;
        }

        --size;
        return cur.value;
    }

    public int size() {
        return this.size;
    }

    private int randomLevel() {
        int level = 1;
        while (r.nextDouble() < p) {
            ++level;
        }

        return level;
    }

    private static class Node<K extends Comparable<K>, V> {
        private K key;
        private V value;
        private Map<Integer, Node<K, V>> forward;

        public Node(K key, V value) {
            this.key = key;
            this.value = value;
            forward = new HashMap<>();
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }

            if (o == null) {
                return false;
            }

            if (getClass() != o.getClass()) {
                return false;
            }

            @SuppressWarnings("unchecked")
            Node<K, V> x = (Node<K, V>) o;
            return Objects.equals(this.key, x.key) && Objects.equals(this.value, x.value);
        }
    }
}