forked from PacktPublishing/Go-Systems-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash.go
49 lines (42 loc) · 801 Bytes
/
hash.go
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
package main
import (
"fmt"
)
type Node struct {
Value int
Next *Node
}
type HashTable struct {
Table map[int]*Node
Size int
}
func hashFunction(i, size int) int {
return (i % size)
}
func insert(hash *HashTable, value int) int {
index := hashFunction(value, hash.Size)
element := Node{Value: value, Next: hash.Table[index]}
hash.Table[index] = &element
return index
}
func traverse(hash *HashTable) {
for k := range hash.Table {
if hash.Table[k] != nil {
t := hash.Table[k]
for t != nil {
fmt.Printf("%d -> ", t.Value)
t = t.Next
}
fmt.Println()
}
}
}
func main() {
table := make(map[int]*Node, 10)
hash := &HashTable{Table: table, Size: 10}
fmt.Println("Number of spaces:", hash.Size)
for i := 0; i < 95; i++ {
insert(hash, i)
}
traverse(hash)
}