我正在嘗試使用鏈接來實現哈希表,并且不使用任何庫(除了我的代碼中已有的庫),但我陷入了困境。由于某種原因,數據(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 回答

繁星淼淼
TA貢獻1775條經驗 獲得超11個贊
您應進行兩項更改:
您應該使用哈希函數來獲取鍵并保持原樣值。
從插入中刪除index=key%100,而是使用傳遞的key進行遍歷。
希望這可以幫助。
- - - - - - - - - - - - - 編輯 - - - - - - - - - -
要打印鏈接列表中的實際值,請重寫 Node 類中的 toString() 方法并返回鍵值的字符串表示形式。
添加回答
舉報
0/150
提交
取消