Связанный список для каждого местоположения в массиве
Я работаю над заданием и столкнулся с проблемой с моим кодом. В задании мы должны взять ряд чисел, хэшировать их, а затем поместить их в массив, где каждое местоположение является связанным списком. Я написал классы для связанного списка (называемого 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.
}
1 ответ:
Ваша логика вставки перевернута. Вместо
current = anArray[hash];
Это должно быть
anArray[hash] = current;
Я считаю, что вы также должны вызывать
insertMyList(current, anArray)
независимо от того, было ли расположение массива изначально нулевым, поэтому логика должна бытьif(anArray[hash] == null) { anArray[hash] = new MyList(); } insertMyList(anArray[hash], anArray);