哈希解读概念理解

 哈希表(散列表):是根据关键码值(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("输入错误")
		}

	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值