61 lines
1.1 KiB
Go
61 lines
1.1 KiB
Go
package main
|
|
|
|
const ArraySize = 7
|
|
|
|
// HashTable structure
|
|
type HashTable struct {
|
|
array [ArraySize]*bucket
|
|
}
|
|
|
|
// bucket structure
|
|
type bucket struct {
|
|
key string
|
|
value int
|
|
next *bucket
|
|
}
|
|
|
|
// Insert will take in a key and will add the item to the hash table array.
|
|
func (h *HashTable) Insert(key string, value int) {
|
|
index := hash(key)
|
|
h.array[index] = &bucket{key, value, h.array[index]}
|
|
}
|
|
|
|
// Search will take in a key and RETURN true if that key is stored in the hash table.
|
|
func (h *HashTable) Search(key string) bool {
|
|
index := hash(key)
|
|
b := h.array[index]
|
|
for b != nil {
|
|
if b.key == key {
|
|
return true
|
|
}
|
|
b = b.next
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Delete will take in a key and DELETE it from the hash table.
|
|
func (h *HashTable) Delete(key string) {
|
|
index := hash(key)
|
|
b := h.array[index]
|
|
if b.key == key {
|
|
h.array[index] = b.next
|
|
return
|
|
}
|
|
for b.next != nil {
|
|
if b.next.key == key {
|
|
b.next = b.next.next
|
|
return
|
|
}
|
|
b = b.next
|
|
}
|
|
}
|
|
|
|
// hash is the basic hashing function.
|
|
func hash(key string) int {
|
|
sum := 0
|
|
for _, v := range key {
|
|
sum += int(v)
|
|
}
|
|
return sum % ArraySize
|
|
}
|