gpt4 book ai didi

java - 使用链表进行散列

转载 作者:行者123 更新时间:2023-12-02 09:30:58 25 4
gpt4 key购买 nike

我正在尝试使用链接实现哈希表,并且不使用任何库(除了我的代码中已有的库),但我陷入了困境。由于某种原因,数据(100 行整数)没有被添加到列表中,如打印时所见,除了第二个位置的一个(我假设我需要一个 toString() 方法。)我可以获得有关如何实现这项工作的任何提示或解决方案吗?

提前致谢!

主+数组声明:

static LinkedList<Node> hashTable[] = new LinkedList[100];

static class Node {

int value;
int key;
}

public static void main(String[] args) throws FileNotFoundException {

File f = new File("Ex5.txt");

Scanner scan = new Scanner(f);

if (f.exists() == false) {
System.out.println("File doesn't exist or could not be found.");
System.exit(0);
}

while (scan.hasNextInt()) {
int n = scan.nextInt();
insert(1, hashFunction(n));
}

for (int i = 0; i < 100; ++i) {
System.out.println(hashTable[i]);
}
}

插入函数:

public static void insert(int key, int value) {
int index = key % 100;
LinkedList<Node> items = hashTable[index];

if (items == null) {
items = new LinkedList<>();

Node item = new Node();
item.key = key;
item.value = value;

items.add(item);

hashTable[index] = items;
} else {
for (Node item : items) {
if (item.key == key) {
item.value = value;
return;
}
}

Node item = new Node();
item.key = key;
item.value = value;

items.add(item);
}
}

哈希函数:

public static int hashFunction(int value) {
int hashKey = value % 100;
return hashKey;
}

最佳答案

您应进行两项更改:

  1. 您应该使用哈希函数来获取 key 并保持值不变。

  2. 从插入中删除index=key%100,而是使用传递的 key 遍历。

希望这有帮助。

-------------------------- 编辑 --------------------

要打印链接列表中的实际值,请重写 Node 类中的 toString() 方法并返回键值对的字符串表示形式。

关于java - 使用链表进行散列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57989488/

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