【问题标题】:Quick Hash Table using Chaining使用链接的快速哈希表
【发布时间】:2011-12-03 02:28:44
【问题描述】:

试图更好地理解哈希表上的链接。寻找一个简单的表,该表对一个值进行散列,并且只将一个整数与散列的值相关联。这是相关问题的示例代码...

      /* hash string value return int */
      public int hashFunction(String D) {
          char[] Thing = D.toCharArray();
          for(int i=0; i < Thing.length; i++){
             index += Thing[i]; }
          return index % TABLE_SIZE;          
      }

      /* hash string value return void */
      public void hashFunction(String D) {
        char[] Thing = D.toCharArray();
        for(int i=0; i < Thing.length; i++){
         index += Thing[i];}
        int hash = index % TABLE_SIZE;
        if(table[hash] == null){
          table[hash] = new HashEntry( Level,  Value );
        }        
        else{
          table[hash].setNext(nd);
        }
      }

      /* miscellaneous code snippet */
      if(table[hash] == null){
        table[hash] = new HashEntry();
      }

      else if (Data.compareTo("VAR") == 0) {
          Data = inFile.next();   
            char[] Thing = Data.toCharArray();
            for(int i=0; i < Thing.length; i++){
            hash += Thing[i];}
            hash = hash % TABLE_SIZE;           
            hm.setIntoHashTable(hash);      
                Data = inFile.next();
                    if(Data.compareTo("=") == 0) {
                    Data = inFile.next();
                    int value = Integer.parseInt(Data);
                    hm.getIntoHashTable(he.setValue(value));
                }
      }

【问题讨论】:

  • 您可以创建int generateHash(String D)int insertIntoHashTable(String D)generateHash 是您的哈希函数。 insertIntoHashTable 会先调用generateHash 然后有插入逻辑
  • 你能描述一下你的哈希函数吗? int level 是什么,你说的另一个 int 是什么?
  • 请不要大声提问...
  • 请不要破坏这个问题

标签: hash chaining


【解决方案1】:

当您在索引中发生冲突时会发生链接。

假设您有一个 TABLE_SIZE=10

现在你必须存储字符串abc,所以你得到的哈希是4

现在当你要存储字符串 cba 时,你最终会得到相同的哈希 4

所以现在要将cba 存储在同一索引中,您将创建一个列表并将其存储在索引4

列表将同时包含abcbca。这个列表叫做chain,这个在同一个哈希中存储多个值的过程叫做Chaining

伪代码如下:

if(table[hash] == null)
  table[hash] = new ArrayList<HashEntry>();//APPEND ON TO THE LOCATION ALREADY THERE!
table[hash].add(new HashEntry());

该表将被声明为:

@SuppressWarnings("unchecked")
List<HashEntry>[] table = new List[TABLE_SIZE];

您可能不得不取消警告,因为数组和泛型运行不顺利。

【讨论】:

  • 你能描述一下你的哈希函数吗?什么是 int 级别,你说的另一个 int 是什么?
猜你喜欢
  • 1970-01-01
  • 2010-10-04
  • 2012-05-06
  • 2013-09-12
  • 2014-03-26
  • 2021-12-26
  • 1970-01-01
  • 2014-08-18
  • 2015-01-11
相关资源
最近更新 更多