gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:02:43 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com