2

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

}
4

1 回答 1

3

您的插入逻辑是相反的。代替

current = anArray[hash];

它应该是

anArray[hash] = current;

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

if(anArray[hash] == null) {
    anArray[hash] = new MyList();
}
insertMyList(anArray[hash], anArray);
于 2013-04-10T15:15:36.523 回答