亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用鏈表進行散列

使用鏈表進行散列

互換的青春 2023-08-04 17:32:19
我正在嘗試使用鏈接來實現哈希表,并且不使用任何庫(除了我的代碼中已有的庫),但我陷入了困境。由于某種原因,數據(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個贊

您應進行兩項更改:

  1. 您應該使用哈希函數來獲取鍵并保持原樣值。

  2. 從插入中刪除index=key%100,而是使用傳遞的key進行遍歷。

希望這可以幫助。

- - - - - - - - - - - - - 編輯 - - - - - - - - - -

要打印鏈接列表中的實際值,請重寫 Node 類中的 toString() 方法并返回鍵值的字符串表示形式。


查看完整回答
反對 回復 2023-08-04
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號