# 你将如何在x语言中实现哈希表？ [关闭]How would you implement a hashtable in language x? [closed]

## 9 个回复9

### ===============>>#1 票数：19

``````int ComputeHash(char* key)
{
int hash = 5381;
while (*key)
hash = ((hash << 5) + hash) + *(key++);
return hash % hashTable.totalBuckets;
}
``````

``````typedef struct HashTable{
HashTable* nextEntry;
char*      key;
char*      value;
}HashBucket;

typedef struct HashTableEntry{
int totalBuckets;       // Total number of buckets allocated for the hash table
HashTable** hashBucketArray; // Pointer to array of buckets
}HashTableEntry;
HashTableEntry hashTable;

bool InitHashTable(int totalBuckets)
{
if(totalBuckets > 0)
{
hashTable.totalBuckets = totalBuckets;
hashTable.hashBucketArray = (HashTable**)malloc(totalBuckets * sizeof(HashTable));
if(hashTable.hashBucketArray != NULL)
{
memset(hashTable.hashBucketArray, 0, sizeof(HashTable) * totalBuckets);
return true;
}
}
return false;
}

{
int offset = ComputeHash(key);
if(hashTable.hashBucketArray[offset] == NULL)
{
hashTable.hashBucketArray[offset] = NewNode(key, value);
if(hashTable.hashBucketArray[offset] != NULL)
return true;
}

else
{
return true;
}
return false;
}

HashTable* NewNode(char* key, char* value)
{
HashTable* tmpNode = (HashTable*)malloc(sizeof(HashTable));
if(tmpNode != NULL)
{
tmpNode->nextEntry = NULL;
tmpNode->key   = (char*)malloc(strlen(key));
tmpNode->value = (char*)malloc(strlen(value));

strcpy(tmpNode->key, key);
strcpy(tmpNode->value, value);
}
return tmpNode;
}
``````

``````if(InitHashTable(100) == false) return -1;
``````

``````HashTable* FindNode(char* key)
{
int offset = ComputeHash(key);
HashTable* tmpNode = hashTable.hashBucketArray[offset];
while(tmpNode != NULL)
{
if(strcmp(tmpNode->key, key) == 0)
return tmpNode;
tmpNode = tmpNode->nextEntry;
}
return NULL;
}
``````

``````char* value = FindNode("10");
``````

### ===============>>#2 票数：8

<60 LoC中的Java实现

``````import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class HashTable {

class KeyValuePair {

Object key;

Object value;

public KeyValuePair(Object key, Object value) {
this.key = key;
this.value = value;
}
}

private Object[] values;

private int capacity;

public HashTable(int capacity) {
values = new Object[capacity];
this.capacity = capacity;
}

private int hash(Object key) {
return Math.abs(key.hashCode()) % capacity;
}

public void add(Object key, Object value) throws IllegalArgumentException {

if (key == null || value == null)
throw new IllegalArgumentException("key or value is null");

int index = hash(key);

List<KeyValuePair> list;
if (values[index] == null) {
list = new ArrayList<KeyValuePair>();
values[index] = list;

} else {
// collision
list = (List<KeyValuePair>) values[index];
}

}

public Object get(Object key) {
List<KeyValuePair> list = (List<KeyValuePair>) values[hash(key)];
if (list == null) {
return null;
}
for (KeyValuePair kvp : list) {
if (kvp.key.equals(key)) {
return kvp.value;
}
}
return null;
}

/**
* Test
*/
public static void main(String[] args) {

HashTable ht = new HashTable(100);

for (int i = 1; i <= 1000; i++) {
ht.add("key" + i, "value" + i);
}

Random random = new Random();
for (int i = 1; i <= 10; i++) {
String key = "key" + random.nextInt(1000);
System.out.println("ht.get(\"" + key + "\") = " + ht.get(key));
}
}
}
``````

### ===============>>#3 票数：7

HashTable是一个非常简单的概念：它是一个数组，通过以下方案将键和值对放入（如关联数组）：

### ===============>>#5 票数：1

``````public class HashTable
{
public static int HFunc(int key)
{
return key%128;
}

public boolean Put(Val V)
{

int hashval = HFunc(V.getKey());
hashArr[hashval].Insert(ln);
System.out.println("Inserted!");
return true;
}

public boolean Find(Val V)
{
int hashval = HFunc(V.getKey());
if (hashArr[hashval].getInitial()!=null && hashArr[hashval].search(V)==true)
{
System.out.println("Found!!");
return true;
}
else
{
return false;
}

}
public boolean delete(Val v)
{
int hashval = HFunc(v.getKey());
if (hashArr[hashval].getInitial()!=null && hashArr[hashval].delete(v)==true)
{
System.out.println("Deleted!!");
return true;
}
else
{
System.out.println("Could not be found. How can it be deleted?");
return false;
}
}

public HashTable()
{
for(int i=0; i<hashArr.length;i++)
}

}

class Val
{
private int key;
private int val;
public int getKey()
{
return key;
}
public void setKey(int k)
{
this.key=k;
}
public int getVal()
{
return val;
}
public void setVal(int v)
{
this.val=v;
}
public Val(int key,int value)
{
this.key=key;
this.val=value;
}
public boolean equals(Val v1)
{
if (v1.getVal()==this.val)
{
//System.out.println("hello im here");
return true;
}
else
return false;
}
}

{
private Val obj;
{
this.obj=v;
this.next=next;
}
{
this.obj=null;
this.next=null;
}
public Val getObj()
{
return this.obj;
}
{
this.next = ln;
}

{
return this.next;
}
{
if (ln1.getObj().equals(ln2.getObj()))
{
return true;
}
else
return false;

}

}

{
{
this.initial=null;
}
{
this.initial = initial;
}
{
return this.initial;
}
{
this.initial = ln;
ln.setNext(temp);
}
public boolean search(Val v)
{
if (this.initial==null)
return false;
else
{
while (temp!=null)
{
//System.out.println("encountered one!");
if (temp.getObj().equals(v))
return true;
else
temp=temp.getNext();
}
return false;
}

}
public boolean delete(Val v)
{
if (this.initial==null)
return false;
else
{
if (prev.getObj().equals(v))
{
this.initial = null;
return true;
}
else
{
while (temp!=null)
{
if (temp.getObj().equals(v))
{
prev.setNext(temp.getNext());
return true;
}
else
{
prev=temp;
temp=temp.getNext();
}
}
return false;
}
}
}
}
``````

### ===============>>#6 票数：0

• 哈希表是固定大小还是动态的？
• 使用什么类型的哈希函数？
• 哈希表调整大小时是否存在任何性能限制？

### ===============>>#7 票数：0

F＃中的最小实现，作为从给定的键值对序列构建哈希表的函数，并返回一个函数，该函数在哈希表中搜索与给定键关联的值：

``````> let hashtbl xs =
let spine = [|for _ in xs -> ResizeArray()|]
let f k = spine.[abs(k.GetHashCode()) % spine.Length]
Seq.iter (fun (k, v) -> (f k).Add (k, v)) xs
fun k -> Seq.pick (fun (k', v) -> if k=k' then Some v else None) (f k);;
val hashtbl : seq<'a * 'b> -> ('a -> 'b) when 'a : equality
``````

### ===============>>#8 票数：0

``````tmpNode->key   = (char*)malloc(strlen(key)+1);   //must have +1 for '\0'
tmpNode->value = (char*)malloc(strlen(value)+1); //must have +1
strcpy(tmpNode->key, key);
strcpy(tmpNode->value, value);
``````

``````HashNode* AppendLinkedNode(HashNode* ptr, char* key, char* value)
{
while (ptr->nextEntry!=NULL)
{
if (strcmp(ptr->value,value)==0) return NULL;
ptr=ptr->nextEntry;
}
ptr->nextEntry=newNode(key,value);
return ptr->nextEntry;
}
``````

• 哈希函数
• 可变桶数
• 碰撞行为