Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

class SkipListNode

class SkipListNode> {

T value;

SkipListNode[] forward;

@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 head;

private int level;

public SkipList() {

this.level = 0;

this.head = new SkipListNode<>(null, MAX_LEVEL);

}

public void addNode(T value) {

@SuppressWarnings("unchecked")

SkipListNode[] update = new SkipListNode[MAX_LEVEL + 1];

SkipListNode current = head;

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 newNode = new SkipListNode<>(value, newLevel);

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 current = head;

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 list = new 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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Records And Database Management

Authors: Jeffrey R Stewart Ed D, Judith S Greene, Judith A Hickey

4th Edition

0070614741, 9780070614741

More Books

Students also viewed these Databases questions

Question

2. Outline the business case for a diverse workforce.

Answered: 1 week ago