哈希表(散列表):是根据关键码值(key value)而直接进行访问的数据结构,也就是说它通过把关键码映射到表中的一个位置来访问记录,以加快查找的速度,这个映射函数叫做散列函数 存放记录的数组叫做散列表
// 将员工的信息id和姓名 加入 当输入id是显示全部信息 要求:不使用数据库 尽量节省内存 速度越快越好 =》哈希 // 将员工的信息id和姓名 加入 当输入id是显示全部信息 要求:不使用数据库 尽量节省内存 速度越快越好 =》哈希 package main import( "fmt" ) type Emp struct { id int name string next *Emp } // 方法待定 type EmpLink struct { Head *Emp // 不带表头 } //hash table 含有一个链表数组 type hashTable struct { LinkArr [7]EmpLink } func (this *EmpLink) Insert(emp *Emp) { // 考虑三个位置 开头 结尾 和中间 这三个临界点 cur := this.Head var pre *Emp = nil if cur == nil { this.Head = emp return } else { for { if cur == nil { pre.next = emp emp.next = cur break } else { if emp.id < cur.id { pre.next = emp emp.next = cur break } } pre = cur // 前一个 cur = cur.next // 12346789 要插入的是5 pre就是4 } } } func (this *hashTable) Insert(emp *Emp) { linkNo := this.HashFun(emp.id) this.LinkArr[linkNo].Insert(emp) } // 给hashtable 编写insert雇员的方法 func (this *hashTable) HashFun(id int) int { return id % 7 } func (this *hashTable) ShowAll() { for i:= 0;i<len(this.LinkArr)-1;i++ { this.LinkArr[i].ShowLink(i) } } func (this *EmpLink) ShowLink (no int) { if this.Head == nil { fmt.Printf("链表%d数据为空\n",no) return } cur := this.Head for { if cur == nil { break } fmt.Printf("id=%d,name=%v=>",cur.id,cur.name) cur = cur.next } fmt.Println() } func main() { key := "" id := 0 name := "" var hashTable hashTable for { fmt.Scanln(&key) switch key { case "input" : fmt.Println("请输入雇员id") fmt.Scanln(&id) fmt.Scanln(&name) emp := &Emp{ id:id, name:name, } hashTable.Insert(emp) case "show" : hashTable.ShowAll() case "exit": default : fmt.Println("输入错误") } } }