跳表的实现 Java

5 篇文章 1 订阅

一、什么是跳表?

我们经常可以看到跳表这个词,但是却对里面的数据结构缺乏了解。相比于红黑树,跳表本身是一种基于链表的数据结构,所以他本身的插入和删除效率很高,而查找效率和红黑树相当,都是 O ( l o g 2 n ) O(log_2n) O(log2n)。我们来看一下跳表的结构


可以明显看到,跳表就是一种典型的以空间换时间的数据结构。
该算法与哈希算法的另一个区别就是:哈希算法不会保存数据的顺序,而跳表内的所有元素都是排序的。因此对于跳表进行遍历会得到一组有序的数据。

在JDK内部,也使用了该数据结构,比如ConcurrentSkipListMap,ConcurrentSkipListSet等。下面我们主要介绍ConcurrentSkipListMap。说到ConcurrentSkipListMap,我们就应该比较HashMapConcurrentHashMapConcurrentSkipListMap这三个类来讲解。它们都是以键值对的方式来存储数据的。HashMap线程不安全的,而ConcurrentHashMapConcurrentSkipListMap线程安全的,它们内部都使用无锁CAS算法实现了同步。ConcurrentHashMap中的元素是无序的,ConcurrentSkipListMap中的元素是有序的。

二、跳表的实现

对于每一个跳表的节点,我们的数据结构如下:

由right指针和down指针和它的保存值val构成,代码中会详细解释为什么需要这种结构

class Skiplist {

    // 头指针,左上角
    Node head = new Node(null, null, 0);

    // 记忆栈, 用于在每层找到 空指针或保存值大于插入值的前驱结点
    Node[] stack = new Node[64];

    Random rand = new Random();

    static class Node {
        Node right, down;
        int val;
        public Node(Node r, Node d, int val) {
            this.right = r;
            this.down = d;
            this.val = val;
        }
    }

    public Skiplist() {

    }
    
    public boolean search(int target) {
        for(Node p = head; p != null; p = p.down) {
            while (p.right != null && p.right.val < target){
                p = p.right;
            }

            if(p.right != null && p.right.val == target)
                return true;
        }
        return false;
    }
    
    public void add(int num) {
        int lv = -1;
        for(Node p = head; p != null; p = p.down) {
            while(p.right != null && p.right.val < num) {
                p = p.right;
            }
            stack[++lv] = p;
        }

        boolean inseartUp = true;
        Node downNode = null;

        while(inseartUp && lv >= 0) {
            Node node = stack[lv--];
            node.right = new Node(node.right, downNode, num);
            downNode = node.right;
            inseartUp = (rand.nextInt() & 1) == 0;
        }

        if (inseartUp) {
            head = new Node(new Node(null, downNode, num), head, 0);
        }
    }
    
    public boolean erase(int num) {
        boolean exist = false;
        for(Node p = head; p != null; p = p.down) {
            while(p.right != null && p.right.val < num) {
                p = p.right;
            }

            if (p.right != null && p.right.val == num) {
                exist = true;
                p.right = p.right.right;
            }
        }

        return exist;
    }
}

/**
 * Your Skiplist object will be instantiated and called as such:
 * Skiplist obj = new Skiplist();
 * boolean param_1 = obj.search(target);
 * obj.add(num);
 * boolean param_3 = obj.erase(num);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值