public class SkipList {
class Node{
int value = -1;
int level;
//这里用的数组
Node[] next;
public Node(int value, int level) {
this.value = value;
this.level = level;
next = new Node[level];
}
}
//参数分别为 最大层数,dumn头节点,节点的个数,层数
int maxValue = 16;
Node head = new Node(-1,16);
int size = 0;
int levelCount = 1;
//很明显 每一层里面使用next(这里固定住了i) 而每一层之间使用下标(也就是i)
//这里node直接使用了数组 可以理解成全局只有一个next对象?
//next[0]表示什么?
public Node find(int value){
Node temp = head;
//i代表横着走 由于node结构本来就是 node【】 所有从上一定可以往下
for (int i = levelCount-1; i >= 0 ; i--) {
while(temp.next[i] != null && temp.value < value){
temp = temp.next[i];
System.out.println(temp.value+" "+i);
}
}
if(temp.next[0] != null && temp.next[0].value == value){
System.out.println("查找成功");
return temp.next[0];
}else{
System.out.println("查无此数");
return null;
}
}
public void insert(int value){
int level = getLevel();
Node newNode = new Node(value, level);
Node[] update = new Node[level];
Node temp = head;
for (int i = level-1; i >= 0 ; i--) {
while(temp.next[i] != null && temp.next[i].value < value){
//永远都是需要一个数组的
temp = temp.next[i];
}
update[i] = temp;
}
for (int i = 0; i < level; i++) {
newNode.next[i] = update[i].next[i];
update[i].next[i] = newNode;
}
if(level > levelCount){
levelCount = level;
}
size++;
System.out.println(value+"插入成功");
}
public void del(int value){
Node[] update = new Node[levelCount];
Node temp = this.head;
for (int i = levelCount-1; i >= 0 ; i--) {
while (temp.next[i] != null && temp.next[i].value < value){
temp = temp.next[i];
}
update[i] = temp;
}
if(temp.next[0]!=null && temp.next[0].value == value){
size -- ;
System.out.println(value + "删除成功");
for (int i = levelCount-1; i >= 0 ; i--) {
if(update[i].next[i] != null && update[i].next[i].value == value){
update[i].next[i] = update[i].next[i].next[i];
}
}
}
}
private int getLevel() {
int level = 1;
while (true){
int t = (int)(Math.random()*100);
if(t%2 == 0){
level++;
}else{
break;
}
}
System.out.println("当前level为"+level);
return level;
}
public void printAll(){
Node temp = head;
//直接输出最底下那层
while(temp.next[0] != null){
System.out.println(temp.next[0].value+" ");
temp = temp.next[0];
}
}
public static void main(String[] args) {
SkipList skipList = new SkipList();
for (int i = 0; i < 2; i++) {
skipList.insert(i);
}
skipList.printAll();
skipList.del(3);
skipList.printAll();
System.out.println("************************************************");
System.out.println(skipList.find(3));
}
}