-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhash_table.go
98 lines (84 loc) · 1.71 KB
/
hash_table.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import "fmt"
const TABLE_SIZE = 10
type Node struct {
key int
value int
next *Node
}
type HashTable struct {
table [TABLE_SIZE]*Node
}
// 多项式哈希函数
func (h *HashTable) hash(key int) int {
hash := 0
base := 31
for key > 0 {
hash = (hash*base + key%10) % TABLE_SIZE
key /= 10
}
return hash
}
func (h *HashTable) insert(key int, value int) {
index := h.hash(key)
newNode := &Node{key: key, value: value}
newNode.next = h.table[index]
h.table[index] = newNode
}
func (h *HashTable) search(key int) int {
index := h.hash(key)
current := h.table[index]
for current != nil {
if current.key == key {
return current.value
}
current = current.next
}
return -1
}
func (h *HashTable) delete(key int) {
index := h.hash(key)
current := h.table[index]
var prev *Node
for current != nil {
if current.key == key {
if prev == nil {
h.table[index] = current.next
} else {
prev.next = current.next
}
return
}
prev = current
current = current.next
}
}
func (h *HashTable) printTable() {
for i, node := range h.table {
if node != nil {
fmt.Printf("Index %d: ", i)
for node != nil {
fmt.Printf("[%d:%d] ", node.key, node.value)
node = node.next
}
fmt.Println()
}
}
}
func main() {
hashTable := &HashTable{}
hashTable.insert(1, 100)
hashTable.insert(2, 200)
hashTable.insert(3, 300)
fmt.Println("Search key 2:", hashTable.search(2))
hashTable.delete(2)
fmt.Println("After deleting key 2:")
hashTable.printTable()
}
/*
jarry@MacBook-Pro hash % go run hash_table.go
Search key 2: 200
After deleting key 2:
Index 1: [1:100]
Index 3: [3:300]
*/