一、什么是跳表?
我们经常可以看到跳表这个词,但是却对里面的数据结构缺乏了解。相比于红黑树,跳表本身是一种基于链表的数据结构,所以他本身的插入和删除效率很高,而查找效率和红黑树相当,都是 O ( l o g 2 n ) O(log_2n) O(log2n)。我们来看一下跳表的结构
可以明显看到,跳表就是一种典型的以空间换时间的数据结构。
该算法与哈希算法的另一个区别就是:哈希算法不会保存数据的顺序,而跳表内的所有元素都是排序的。因此对于跳表进行遍历会得到一组有序的数据。
在JDK内部,也使用了该数据结构,比如ConcurrentSkipListMap
,ConcurrentSkipListSet
等。下面我们主要介绍ConcurrentSkipListMap
。说到ConcurrentSkipListMap
,我们就应该比较HashMap
,ConcurrentHashMap
,ConcurrentSkipListMap
这三个类来讲解。它们都是以键值对的方式来存储数据的。HashMap
是线程不安全的,而ConcurrentHashMap
和ConcurrentSkipListMap
是线程安全的,它们内部都使用无锁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);
*/