目录
import "hash/fnv"
1.结构定义
type HashItem struct {
key string
value int
next *HashItem
}
type HashTable struct {
data [256]*HashItem
}
2.GenerateHash()
func GenerateHash(s string) uint8 {
hash := fnv.New32a()
hash.Write([]byte(s))
return uint8(hash.Sum32() % 256)
}
3.Add()
func (table *HashTable) Add(key string, i int) {
position := GenerateHash(key)
if table.data[position] == nil {
table.data[position] = &HashItem{key: key, value: i}
}
current := table.data[position]
if current.next != nil {
current = current.next
}
current.next = &HashItem{key: key, value: i}
}
4.Get()
func (table *HashTable) Get(key string) (int, bool) {
position := GenerateHash(key)
current := table.data[position]
for current != nil {
if current.key == key {
return current.value, true
}
current = current.next
}
return 0, false
}
5.Set()
func (table *HashTable) Set(key string, i int) bool {
position := GenerateHash(key)
current := table.data[position]
for current != nil {
if current.key == key {
current.value = i
return true
}
current = current.next
}
return false
}
6.Remove()
func (table *HashTable) Remove(key string) bool {
position := GenerateHash(key)
if table.data[position] == nil {
return false
}
if table.data[position].key == key {
table.data[position] = table.data[position].next
return true
}
current := table.data[position]
for current.next != nil {
if current.next.key == key {
current.next = current.next.next
return true
}
current = current.next
}
return false
}