使用链表进行散列
Hashing using a linkedlist
我正在尝试使用链接而不使用任何库(我的代码中已有的库除外)来实现哈希表,但我遇到了困难。出于某种原因,数据(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;
}
您应进行两项更改:
您应该使用散列函数来获取键并保持值不变。
从插入中删除 index=key%100,而是使用传递的键
遍历.
希望对您有所帮助。
------------------------编辑---------------- --
要在链表中打印实际值,请覆盖节点中的 toString() 方法 Class 和 return 键值对的字符串表示形式。
我正在尝试使用链接而不使用任何库(我的代码中已有的库除外)来实现哈希表,但我遇到了困难。出于某种原因,数据(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;
}
您应进行两项更改:
您应该使用散列函数来获取键并保持值不变。
从插入中删除 index=key%100,而是使用传递的键 遍历.
希望对您有所帮助。
------------------------编辑---------------- --
要在链表中打印实际值,请覆盖节点中的 toString() 方法 Class 和 return 键值对的字符串表示形式。