Escolar Documentos
Profissional Documentos
Cultura Documentos
Structure
Mugurel Ionu Andreica
Spring 2012
Operations
put(key, value)
Inserts the pair (key, value) in the hash table
If a pair (key, value) (with the same key) already
exists, then value is replaced by value
We say that the value value is associated to the key
key
get(key)
Returns the value associated to the key key
If no value is associated to key, then an error occurs
hasKey(key)
Returns 1 if the key key exists in the hash table, and 0
otherwise
Example
put(3, 7.9)
put(2, 8.3)
get(3) -> returns 7.9
put(3, 10.2)
get(3) -> returns 10.2
get(2) -> returns 8.3
hasKey(5) -> returns 0
hasKey(2) -> returns 1
get(5) -> generates an error
Possible implementation
Maintain an array H[HMAX] of linked lists
The info field of each element of a list consists of a struct containing a key
and a value
put(k, v)
Searches for the key k in the list H[hkey=hash(k)]
If the key is found, then we replace the value by v
If the key is not found, then we insert the pair (k,v) in H[hkey]
get(k)
Search for the key k in H[hkey=hash(k)]
If it finds the key, then it returns its associated value; otherwise, an error
occurs
hasKey(k)
Search for the key k in H[hkey=hash(k)]
If it finds the key, then it returns 1; otherwise, it returns 0
~Hashtable() {
for (int i = 0; i < HMAX; i++) {
while (!H[i].isEmpty())
H[i].removeFirst();
}
delete H;
}
}
while (p != NULL) {
if (p->info.key == key) break;
p = p->next;
}
while (p != NULL) {
if (p->info.key == key)
break;
p = p->next;
}
if (p != NULL)
return p->info.value;
else {
fprintf(stderr, "Error 101 - The key does not
exist in the hashtable\n");
Tvalue x;
return x;
}
}
if (p != NULL)
return 1;
else
return 0;
}
};
hci.put(k1, 10);
hci.put(k2, 20);
printf("%d\n", hci.get(k1));
hci.put(k1, 30);
printf("%d\n", hci.get(k1));
printf("%d\n", hci.get(k2));
printf("%d\n", hci.hasKey(k3));
printf("%d\n", hci.hasKey(k2));
printf("%d\n", hci.get(k4));
return 0;
}
Final remarks
The Hash table is a fundamental data structure in
many situations