我正在完成一项任务,并且遇到了我的代码问题。在赋值中,我们将接收一系列数字,哈希它们,然后将它们放入一个数组中,其中每个位置都是一个链表。我已经为链表(称为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.
}
答案 0 :(得分:3)
您的插入逻辑是相反的。而不是
current = anArray[hash];
应该是
anArray[hash] = current;
我相信你也应该调用insertMyList(current, anArray)
,无论数组位置是否原来为null,所以逻辑应该是
if(anArray[hash] == null) {
anArray[hash] = new MyList();
}
insertMyList(anArray[hash], anArray);