我正在做一项作业,但我的代码遇到了问题。在作业中,我们将获取一系列数字,对它们进行哈希处理,然后将它们放入一个数组中,其中每个位置都是一个链表。我已经为链表(称为 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/