05.4.2 实现查找功能

在这一节中,你将会实现一个 lookup() 函数,使用这个函数可以检查哈希表中是否已经存在某个给定的元素。lookup() 函数基于 traverse() 函数实现,如下所示:

func lookup(hash *HashTable, value int) bool {
    index := hashFunction(value, hash.Size)
    if hash.Table[index] != nil {
        t := hash.Table[index]
        for t != nil {
            if t.Value == value {
                return true
            }
            t = t.Next
        }
    }
    return false
}

你可以在 hashTableLookup.go 源文件中找到上面的代码。执行 hashTableLookup.go 将得到下面的输出:

$ go run hashTableLookup.go
120 is not in the hash table!
121 is not in the hash table!
122 is not in the hash table!
123 is not in the hash table!
124 is not in the hash table!

以上的输出表示 lookup() 函数效果很棒!

Last updated