Created
September 3, 2022 15:19
-
-
Save sagar290/67ff72a88b6c20ca12af3b5c4f4abb27 to your computer and use it in GitHub Desktop.
Hash table, insert, search, delete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
const ArraySize = 7 | |
type HashTable struct { | |
array [ArraySize]*bucket | |
} | |
type bucket struct { | |
head *bucketNode | |
} | |
type bucketNode struct { | |
key string | |
next *bucketNode | |
} | |
// Insert function | |
func (h *HashTable) Insert(key string) { | |
index := hash(key) | |
h.array[index].insert(key) | |
} | |
// Search function | |
func (h *HashTable) Search(key string) bool { | |
index := hash(key) | |
return h.array[index].search(key) | |
} | |
// Delete function | |
func (h *HashTable) Delete(key string) { | |
index := hash(key) | |
h.array[index].delete(key) | |
} | |
func Init() *HashTable { | |
result := &HashTable{} | |
for i := range result.array { | |
result.array[i] = &bucket{} | |
} | |
return result | |
} | |
func hash(key string) int { | |
sum := 0 | |
for _, v := range key { | |
sum += int(v) | |
} | |
return sum % ArraySize | |
} | |
func (b *bucket) insert(k string) { | |
newNode := &bucketNode{key: k} | |
newNode.next = b.head | |
b.head = newNode | |
} | |
func (b *bucket) search(k string) bool { | |
currentNode := b.head | |
for currentNode != nil { | |
if currentNode.key == k { | |
return true | |
} | |
currentNode = currentNode.next | |
} | |
return false | |
} | |
func (b *bucket) delete(k string) { | |
if b.head.key == k { | |
b.head = b.head.next | |
return | |
} | |
previousNode := b.head | |
for previousNode.next != nil { | |
if previousNode.next.key == k { | |
previousNode.next = previousNode.next.next | |
} | |
previousNode = previousNode.next | |
} | |
} | |
func main() { | |
hashTable := Init() | |
list := []string{ | |
"ERIC", | |
"KENNY", | |
"KYLE", | |
"STAN", | |
"RANDY", | |
"BUTTERS", | |
"TOKEN", | |
} | |
for _, v := range list { | |
hashTable.Insert(v) | |
} | |
fmt.Println(hashTable.Search("STAN")) | |
hashTable.Delete("STAN") | |
fmt.Println(hashTable.Search("STAN")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment