请用java写一个跳表
下面是一个简单的Java实现跳表的示例代码:
import java.util.Random;
class SkipListNode {
int value;
SkipListNode next;
SkipListNode down;
public SkipListNode(int value) {
this.value = value;
this.next = null;
this.down = null;
}
}
public class SkipList {
private SkipListNode head;
private Random random;
public SkipList() {
head = new SkipListNode(Integer.MIN_VALUE);
random = new Random();
}
public void insert(int value) {
SkipListNode newNode = new SkipListNode(value);
SkipListNode cur = head;
while (cur != null) {
while (cur.next != null && cur.next.value < value) {
cur = cur.next;
}
if (cur.down != null) {
cur = cur.down;
} else {
break;
}
}
newNode.next = cur.next;
cur.next = newNode;
// 可以根据一定的概率决定是否要添加新的层
while (random.nextDouble() < 0.5) {
SkipListNode newHead = new SkipListNode(Integer.MIN_VALUE);
newHead.down = head;
head = newHead;
SkipListNode newCur = head;
while (cur != null) {
SkipListNode newNext = new SkipListNode(value);
newNext.next = cur.next;
cur.next = newNext;
newCur.down = newNext;
newCur = newCur.next;
cur = cur.down;
}
}
}
public boolean search(int value) {
SkipListNode cur = head;
while (cur != null) {
while (cur.next != null && cur.next.value < value) {
cur = cur.next;
}
if (cur.next != null && cur.next.value == value) {
return true;
}
cur = cur.down;
}
return false;
}
public boolean delete(int value) {
SkipListNode cur = head;
boolean found = false;
while (cur != null) {
while (cur.next != null && cur.next.value < value) {
cur = cur.next;
}
if (cur.next != null && cur.next.value == value) {
cur.next = cur.next.next;
found = true;
}
cur = cur.down;
}
return found;
}
public void printList() {
SkipListNode cur = head;
while (cur != null) {
SkipListNode node = cur;
while (node != null) {
System.out.print(node.value + " ");
node = node.next;
}
System.out.println();
cur = cur.down;
}
}
public static void main(String[] args) {
SkipList skipList = new SkipList();
skipList.insert(1);
skipList.insert(4);
skipList.insert(2);
skipList.insert(3);
skipList.printList();
System.out.println("Search 2: " + skipList.search(2));
System.out.println("Search 5: " + skipList.search(5));
skipList.delete(2);
skipList.printList();
}
}
这个示例代码实现了一个简单的跳表类SkipList,其中使用SkipListNode表示跳表的节点。在SkipList类中,实现了插入insert、搜索search和删除delete等操作。在main方法中演示了插入了四个元素并打印跳表的结构,然后进行了搜索和删除操作,并打印修改后的跳表结构
原文地址: http://www.cveoy.top/t/topic/iSPQ 著作权归作者所有。请勿转载和采集!