I have this code for a skip list I modified from a source online, the add(x) method somewhat works.
add(5);
add(4);
add(7);
it works when you add a number like 5, then any number smaller than the last number, like 4 but once it get to 7 or any number larger than the previous it gets stuck in a loop, and I cannot see why.
package assignment1;
public class Node {
public static int item;
public static Node[] next;
public static int MAX_LEVEL = 6;
public static int level;
public static int n;
public static Node head = new Node(MAX_LEVEL, 0);
public Node(int level, int value){
next = new Node[level + 1];
this.item = value;
}
public static int randomLevel() {
int lvl = (int)(Math.log(1. * -Math.random()) / Math.log(1. * -0.5));
return Math.min(lvl, MAX_LEVEL);
}
public static void add(int value){
Node current = head;
Node[] update = new Node[MAX_LEVEL + 1];
for (int i = level; i >= 0; i--) {
while (current.next[i] != null && current.next[i].item - value < 0) {
current = current.next[i];
}
update[i] = current;
}
current = current.next[0];
if (current == null || current.item != value) {
int lvl = randomLevel();
if (lvl > level) {
for (int i = level + 1; i <= lvl; i++) {
update[i] = head;
}
level = lvl;
}
current = new Node(lvl, value);
for (int i = 0; i <= lvl; i++) {
current.next[i] = update[i].next[i];
update[i].next[i] = current;
}
n++;
}
}
public static void remove(int value){
Node current = head;
Node[] update = new Node[MAX_LEVEL + 1];
for (int i = level; i >= 0; i--) {
while (current.next[i] != null && current.next[i].item - value < 0) {
current = current.next[i];
}
update[i] = current;
}
current = current.next[0];
if (current.item == value) {
for (int i = 0; i <= level; i++) {
if (update[i].next[i] != current){
break;
}
update[i].next[i] = current.next[i];
}
while (level > 0 && head.next[level] == null) {
level--;
}
n--;
}
}
public static void list(){
Node current = head;
System.out.print("[");
for (int i = 0; i < n; i++){
System.out.print(current.item + ",");
current = current.next[0];
}
System.out.print("]");
}
public static void main(String[] args){
add(10);
add(9);
add(8);
add(7);
add(6);
add(5);
add(4);
add(3);
add(2);
add(1);
list();
}
}
EDIT: I uploaded the entire code I developed, the code is from a Textbook of mine that is in Pseudocode, it needed to be adapted into Java format. I cannot see why its failing.