java - 数组中每个位置的链表

标签 java arrays list linked-list hashtable

我正在做一项作业,但我的代码遇到了问题。在作业中,我们将获取一系列数字,对它们进行哈希处理,然后将它们放入一个数组中,其中每个位置都是一个链表。我已经为链表(称为 MyList)编写了类,并编写了代码,如果该数组位置中没有任何内容,则将一个整数放入数组中。我遇到的问题是,当我尝试打印时,数组中的每个位置继续得到“null”。我在这里犯了一个愚蠢的错误还是我的方法有缺陷?谢谢。

public class MyHashTab {

public MyHashTab(int initialCapacity, MyList[] anArray) {

}


public static void insert(int searchKey, MyList[] anArray) {

    int hash = searchKey % anArray.length;

    MyList current = new MyList();

    current.iData = searchKey;

    if (anArray[hash] == null) {

        current = anArray[hash];

    }else{

        insertMyList(current, anArray);

    }

}

public static void insertMyList(MyList current, MyList[] anArray) {

    System.out.println("We are here.");
}

public static void printHash(MyList[] anArray) {

    System.out.println("The generated hash table with separate chaining is: ");

    for (int i = 0; i < anArray.length; i++) {

        System.out.println("The items for index[" + i + "]: " + anArray[i]);

    }
}

}

public class MyList {

int iData; // This integer is used as a key value, and as a way to see the actual node instead of it's memory address. 
MyList current;
MyList previous; // This is a pointer to a nodes left child. Pointing seems rude, but they sometimes point to null which, as well know, is less rude. 
MyList next; // This is a pointer to a nodes right child. 

}

最佳答案

您的插入逻辑颠倒了。而不是

current = anArray[hash];

应该是

anArray[hash] = current;

我相信你也应该调用 insertMyList(current, anArray) 无论数组位置最初是否为空,所以逻辑应该是

if(anArray[hash] == null) {
    anArray[hash] = new MyList();
}
insertMyList(anArray[hash], anArray);

关于java - 数组中每个位置的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15929754/

相关文章:

java - 从Spring App(docker-compose)在Mongodb连接上获取 “Exception opening socket”

java - 使用 JAXB 的 Jersey Web 服务中的 xml 语法无效

python - 不同形状数组的Numpy距离计算

arrays - Firebase Firestore : Append/Remove items from document array

python - N 个随机、连续且不重叠的子序列,每个子序列的长度

java - 了解 Hibernate 中的 hibernate.bytecode.use_reflection_optimizer 属性

java - 使用 Comparable、Java 进行 Collections.sort 时出错

Java.util.Arrays.sort - 什么类型?

r - 通过使用另一列索引到列表中来在数据框中创建一个新列?

python - 在 Python 中从一组数字创建 "slice notation"样式列表