哈希表

散列表(Hashtable,也叫哈希表),是根据关键码值(Keyvalue)而直接进行访问的数据结构。也就是说,它通
过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做散列函数,存放记录的数组
叫做散列表。

google 公司的一个上机题:
有一个公司,当有新的员工来报道时,要求将该员工的信息加入(id,性别,年龄,名字,住址…),当输入该员工的 id 时, 要求查找到该员工的 所有信息.
要求:

  1. 不使用数据库,速度越快越好=>哈希表(散列)
  2. 添加时,保证按照 id 从低到高插入
  3. 使用链表来实现哈希表, 该链表不带表头[即: 链表的第一个结点就存放雇员信息]

具体实现如下:

//哈希表管理多条链表
class HashTab {
//存储链表
private EmpLinkedList[] empLinkedLists;
private int size;//链表的数量

//初始化
public HashTab(int size)
{
this.size=size;
empLinkedLists=new EmpLinkedList[size];
//创建链表
for (int i = 0; i <size ; i++) {
empLinkedLists[i]=new EmpLinkedList();
}
}

//添加雇员结点
public void add(Emp emp) {
//算出存储在哪个链表
int empLinklistNo = hashFun(emp.id);
//把结点添加到固定的链表里
empLinkedLists[empLinklistNo].add(emp);
}
//显示数据
public void list(){
for (int i = 0; i <size ; i++) {
//显示每个链表的数据
empLinkedLists[i].list(i);
}
}
//查找每条链表中,是否有id
public void findEmpByID(int id)
{
//使用散列函数确定链表
int empLinkedNo=hashFun(id);
Emp emp=empLinkedLists[empLinkedNo].findEmpById(id);

if (emp!=null)//找到
{
System.out.printf("在第%d条链表中找到雇员 id=%d\n",(empLinkedNo+1),id);
}else{
System.out.println("在哈希表中,没有找到该雇员");
}
}

//散列函数
public int hashFun(int id)
{
return id%size;
}


}


//一个雇员
class Emp {
public int id;
public String name;
public Emp next;

public Emp(int id, String name) {
this.id = id;
this.name = name;
}
}
//创建链表
class EmpLinkedList {
//头指针
private Emp head; //默认为null

public void add(Emp emp) {
//添加第一个
if (head == null) {
head = emp;
return;
}
//不是第一个,使用辅助结点
Emp curEmp = head;

while (true) {
if (curEmp.next == null) {//到链表最后了
break;
}

curEmp = curEmp.next;//后移
}
//加入
curEmp.next = emp;
}

//遍历获取数据
public void list(int no) {
if (head == null) { //链表为空
System.out.println("第" + (no + 1) + "链表为空");
return;
}
System.out.print("第" + (no + 1) + "链表的信息为");
Emp curemp = head;///辅助指针
while (true) {
System.out.printf("=>id=%d name=%s\t", curemp.id, curemp.name);
if (curemp.next == null) {//末尾结点
break;
}

curemp = curemp.next;//后移
}

System.out.println();
}
//根据id查找
public Emp findEmpById(int id) {
if (head == null) {//判断链表是否为空
System.out.println("链表为空");

return null;
}
///辅助指针
Emp curemp = head;
while (true) {
if (curemp.id == id) { //找到
break;
}

if (curemp.next == null) { //没有找到
curemp = null;
break;
}

curemp = curemp.next;//后移
}

return curemp;
}
}

哈希表_System