Question
class SkipListNode
class SkipListNode
T value;
SkipListNode
@SuppressWarnings("unchecked")
public SkipListNode(T value, int level) {
this.value = value;
this.forward = new SkipListNode[level + 1];
}
}
class SkipList
private static final int MAX_LEVEL = 16;
private SkipListNode
private int level;
public SkipList() {
this.level = 0;
this.head = new SkipListNode<>(null, MAX_LEVEL);
}
public void addNode(T value) {
@SuppressWarnings("unchecked")
SkipListNode
SkipListNode
for (int i = level; i >= 0; i--) {
while (current.forward[i] != null && current.forward[i].value.compareTo(value) < 0) {
current = current.forward[i];
}
update[i] = current;
}
current = current.forward[0];
if (current == null || !current.value.equals(value)) {
int newLevel = randomLevel();
if (newLevel > level) {
for (int i = level + 1; i <= newLevel; i++) {
update[i] = head;
}
level = newLevel;
}
SkipListNode
for (int i = 0; i <= newLevel; i++) {
newNode.forward[i] = update[i].forward[i];
update[i].forward[i] = newNode;
}
}
}
private int randomLevel() {
int lvl = 0;
while (Math.random() < 0.5 && lvl < MAX_LEVEL) {
lvl++;
}
return lvl;
}
public boolean searchKey(T value) {
SkipListNode
for (int i = level; i >= 0; i--) {
while (current.forward[i] != null && current.forward[i].value.compareTo(value) < 0) {
current = current.forward[i];
}
}
current = current.forward[0];
return current != null && current.value.equals(value);
}
}
// Demo
public class SkipListDemo {
public static void main(String[] args) {
SkipList
// Adding nodes
list.addNode(3);
list.addNode(6);
list.addNode(7);
list.addNode(9);
list.addNode(12);
list.addNode(19);
list.addNode(17);
// Searching for a key
System.out.println("Search for 6: " + list.searchKey(6)); // true
System.out.println("Search for 15: " + list.searchKey(15)); // false
}
}Writing this code without changing its function by changing some places
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started