Skip to content

Instantly share code, notes, and snippets.

@sagar290
Last active August 27, 2021 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sagar290/3956b0c0a7f4b06aa0c0e544e49c35ff to your computer and use it in GitHub Desktop.
Save sagar290/3956b0c0a7f4b06aa0c0e544e49c35ff to your computer and use it in GitHub Desktop.
package main
import "fmt"
const ArraySize = 7
// has table hold the array
type HashTable struct {
array [ArraySize]*Bucket
}
// will hold link list
type Bucket struct {
head *BucketNode
}
// bucket node is the link lsit node that hold the key
type BucketNode struct {
key string
next *BucketNode
}
// insert will take the key and add it to the bucket
func (h *HashTable) Insert(key string) {
index := hash(key)
h.array[index].insert(key)
}
// // search will take the key and return true if it exists
func (h *HashTable) Search(key string) bool {
index := hash(key)
return h.array[index].search(key)
}
// // delete will delete the bucket
func (h *HashTable) Delete(key string) {
index := hash(key)
h.array[index].delete(key)
}
// hash
func hash(key string) int {
sum := 0
for _, v := range key {
sum += int(v)
}
return sum % ArraySize
}
// insert will insert key into the bucket
func (b *Bucket) insert(k string) {
if b.search(k) {
fmt.Println(k, "already exist")
return
}
newNode := &BucketNode{key: k}
// make new node and make next node to be the previous
newNode.next = b.head
// point the previous node head to the new node head
b.head = newNode
}
func (b *Bucket) search(key string) bool {
currentNode := b.head
for currentNode != nil {
if currentNode.key == key {
return true
}
currentNode = currentNode.next
}
return false
}
func (b *Bucket) delete(key string) {
if b.head.key == key {
b.head = b.head.next
return
}
previosNode := b.head
for previosNode.next != nil {
if previosNode.next.key == key {
previosNode.next = previosNode.next.next
}
previosNode = previosNode.next
}
}
// init bucket node
func Init() *HashTable {
result := &HashTable{}
for i := range result.array {
result.array[i] = &Bucket{}
}
return result
}
func main() {
hashtable := Init()
list := []string{
"ERIC",
"sagar",
"Sagar",
"SAGAR",
"Junmin Lee",
"Keya",
}
for _, v := range list {
hashtable.Insert(v)
}
fmt.Println(hashtable)
fmt.Println(hashtable.Search("SAGAR"))
hashtable.Delete("Keya")
fmt.Println(hashtable)
fmt.Println(hashtable.Search("Keya"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment