【发布时间】:2015-03-17 23:53:14
【问题描述】:
我有这个代码用于我从在线源修改的跳过列表,add(x) 方法有点工作。
add(5);
add(4);
add(7);
当您添加一个像 5 这样的数字,然后添加任何小于最后一个数字的数字(如 4)时,它会起作用,但是一旦它达到 7 或任何大于前一个数字的数字,它就会陷入循环,我不明白为什么。
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();
}
}
编辑:我上传了我开发的整个代码,代码来自我的一本伪代码教科书,它需要被改编成 Java 格式。我不明白为什么它会失败。
【问题讨论】:
-
会不会和
MAX_LEVEL=6有关系? (提示) -
我没有看到它,我尝试降低/增加
MAX_LEVEL删除它并用randomLevel();替换所有对它的调用 -
你是对的。我很抱歉,我没有做一个很好的分析,并且过早地得出了结论。我发布了一个答案,但我认为这是完全错误的。您从哪里获得在线跳过列表代码?修改 add 方法了吗?
-
我不认为你在 while 循环中正确地迭代了
current,当current.next[i].item-value<0为真时,你就会陷入困境,正如你在代码注释中所说的那样。跨度> -
我不记得我在哪里得到了代码,而且由于我最近重新安装了我的操作系统,所以我丢失了历史记录。我记得的是,我更改最多的是将事物的名称更改为我也使用的格式,以便更好地理解代码。
标签: java skip-lists