這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
Golang 中鏈表的實現及常用操作,資料結構系列原文:flaviocopes.com,翻譯已獲作者授權。
概述
雜湊表是和 map 類型的索引值對儲存方式不同(PHP 中的關聯陣列),它的雜湊函數能根據 key 值計算出 key 在數組中的切確位置(索引)。
區別雜湊表與 Golang 的 map、PHP 中的關聯陣列:
實現
常用操作
使用內建的 map 類型來實現雜湊表,並實現以下常用操作:
1 2 3 4
|
Put() Remove() Get() Size()
|
類似的,建立通用類型 ValueHashTable 來作為雜湊表的結構類型,其中索引值需實現 Stringer 介面。
代碼實現
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
package hashtable
import ( "github.com/cheekybits/genny/generic" "sync" "fmt" )
type Key generic.Type type Value generic.Type
type ValueHashTable struct { items map[int]Value lock sync.RWMutex }
// 使用霍納規則在 O(n) 複雜度內產生 key 的雜湊值 func hash(k Key) int { key := fmt.Sprintf("%s", k) hash := 0 for i := 0; i < len(key); i++ { hash = 31*hash + int(key[i]) } return hash }
// 新增索引值 func (ht *ValueHashTable) Put(k Key, v Value) { ht.lock.Lock() defer ht.lock.Unlock() h := hash(k) if ht.items == nil { ht.items = make(map[int]Value) } ht.items[h] = v }
// 刪除鍵 func (ht *ValueHashTable) Remove(k Key) { ht.lock.Lock() defer ht.lock.Unlock() h := hash(k) delete(ht.items, h) }
// 擷取鍵的雜湊值 func (ht *ValueHashTable) Get(k Key) Value { ht.lock.RLock() defer ht.lock.RUnlock() h := hash(k) return ht.items[h] }
// 擷取雜湊表的大小 func (ht *ValueHashTable) Size() int { ht.lock.RLock() defer ht.lock.RUnlock() return len(ht.items) }
|
測試案例:hashtable_test.go